how to find the position of all the 1s in a logical array in matlab

To find the position of all the 1s in a logical array in MATLAB, you can use indexing in combination with loops and conditional statements. The following code snippet shows how to accomplish this:

main.m
% create a logical array
A = logical([0 1 0; 1 1 1; 0 1 0]);

% find the size of the array
[m, n] = size(A);

% initialize an empty array to store the positions of the 1s
ones_pos = [];

% loop through each element of the array
for i = 1:m
    for j = 1:n
        % if the current element is 1, store its position in the ones_pos array
        if A(i,j) == 1
            ones_pos(end+1,:) = [i j];
        end
    end
end

% display the positions of the 1s
disp(ones_pos);
473 chars
22 lines

In this example, we created a logical array A, which looks like this:

main.m
0 1 0
1 1 1
0 1 0
18 chars
4 lines

Then, we found the size of the array using the size function, and initialized an empty array named ones_pos to store the positions of the 1s.

Next, we used nested loops to iterate through each element of the array. For each element, we checked if its value was equal to 1 using an if statement. If it was, we appended its position to the ones_pos array using the end+1 shorthand notation, which is equivalent to size(ones_pos,1)+1. Finally, we displayed the positions of the 1s using the disp function.

gistlibby LogSnag