MATLAB Answers

0

Search a matrix combined with logical indexing

Asked by Kyra Rubinstein on 11 May 2019
Latest activity Answered by Sulaymon Eshkabilov on 11 May 2019
Hi, I have a matrix A and would like to scan through the values row by row until I find a value above x and stop there. The values prior to x will become 0.
For example: Matrix A = [3 10 2 5; 2 14 5 3] and I want values above 10. The new Matrix I am looking for is = [ 0 0 0 0; 0 14 5 3]. However, I do not want to individually change the first 5 elements of the matrix, I want the code to scan through values. How can I accomplish this?
Thanks!

  0 Comments

Sign in to comment.

2 Answers

Answer by Stephen Cobeldick on 11 May 2019
 Accepted Answer

>> A = [3,10,2,5;2,14,5,3]
A =
3 10 2 5
2 14 5 3
>> N = 10;
>> B = A.*(cumsum(A>N,2)>0)
B =
0 0 0 0
0 14 5 3

  0 Comments

Sign in to comment.


Answer by Sulaymon Eshkabilov on 11 May 2019

Hi,
Here is a quick and a bit crude way of solving this or similar issues:
clearvars
A = [3 10 2 5; 2 14 5 3];
Anew = [A(1,:), A(2,:)]; % Making up row matrix
Index = find(Anew>10); % Finding the elements meeting the set condition (s)
N=numel(Anew); % Countiing the number of elements
AN = [Anew(1:Index-1)*0, Anew(Index:N)]; % Sort out all elements w.r.t. the set conditions
ANnew = [AN(1:N/2); AN( N/2+1:N)] %#ok
Good luck

  0 Comments

Sign in to comment.