如何在MATLAB中为数组元素赋值及将向量最大值设为1
1. How to Assign New Values to Array Elements
Assigning values to array elements in MATLAB is straightforward—you just target the elements you want to modify using indexing, then set them to your desired value. Here are common, practical ways to do it:
- Single element assignment: Use row and column indices to tweak one specific element. For example:
A = [1 2; 3 4]; A(2,1) = 5; % Updates the element at row 2, column 1 to 5 - Batch assignment: Modify a range of elements with colon notation. Perfect for updating entire rows, columns, or blocks:
A(1,:) = 0; % Sets every element in the first row to 0 A(:,2) = 10; % Sets every element in the second column to 10 - Logical indexing: Target elements that meet a condition (super useful for filtering and updating). For example:
A(A < 3) = 0; % Sets all elements smaller than 3 to 0
2. How to Set the Maximum Element of Each Column to 1 (and Others to 0)
Awesome that you already know how to grab the indices of column maxima—let's turn that into your desired matrix B. Here are two efficient methods tailored to your example:
Method 1: Using Indices (Matches Your Current Progress)
If you already have the row indices of each column's maximum, you can initialize a zero matrix and assign 1s directly to those positions. This avoids loops and works cleanly for large matrices:
A = [0.9000 0.1000; 0.0300 0.5800; 0.0100 0.0020]; % Get row indices of the maximum value in each column [~, maxRowIdx] = max(A, [], 1); % Create a zero matrix with the same dimensions as A B = zeros(size(A)); % Convert column-wise indices to MATLAB's internal linear indices linearIndices = sub2ind(size(A), maxRowIdx, 1:size(A,2)); % Assign 1s to the positions of each column's maximum B(linearIndices) = 1;
Method 2: Direct Comparison (No Explicit Indices Needed)
If you don't need the indices for anything else, you can skip grabbing them entirely and compare elements directly to their column's maximum:
A = [0.9000 0.1000; 0.0300 0.5800; 0.0100 0.0020]; % Get the maximum value for each column colMaxes = max(A, [], 1); % Create a logical matrix where elements equal to the column max are true B = (A == colMaxes); % Convert true/false values to 1/0 (numeric matrix) B = double(B);
Note: This method will set all elements equal to the column maximum to 1. If a column has multiple elements with the same highest value, all of them will become 1 (unlike Method 1, which only sets the first occurrence of the maximum to 1).
Content sourced from Stack Exchange, question author: Srishti M

