简体   繁体   中英

Matlab: find a value in a matrix

I have the following matrix:

A= [23 34 45 0 0 0; 21 34 0 0 23 11; 34 23 0 0 0 22]

I want to find if a value is present and if it's present, I want to find the following values.

Eg I want to find in A the value 23, if it's present I want like output a matrix only with 23 and its following values

B= [23 34 45 0 0 0; 0 0 0 0 23 11; 0 23 0 0 0 22]

This is an interesting question, and I have a non-loopy answer, it uses the interesting effect of cumsum and find to great efficiency.

G = zeros(size(A));
T = find(A==23);
G(T) = 1;
mask = cumsum(G,2)>0;

result = mask .* A;

>> result =

23    34    45     0     0     0
 0     0     0     0    23    11
 0    23     0     0     0    22

This is I think, one of the more efficient way of doing this.

========EDIT========

even better, use logical indexing:

B = A.*(cumsum(A==23,2)>0);

Thanks to @obchardon

find() returns the row and the column of the desired value, in your case "23", in matrix A. using a for loop you can copy the value and its following ones:

A = [23 34 45 0 0 0; ...
    21 34 0 0 23 11; ...
    34 23 0 0 0 22];
[r, c] = find(A==23);

B = zeros(3,6);

for i=1:length(r)
    columns = c(i):length(B);
    B(i,columns) = A(r(i),columns);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM