Reputation: 121
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]
Upvotes: 0
Views: 2361
Reputation: 4510
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
Upvotes: 3
Reputation: 673
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;
Upvotes: 1