Clear Filters
Clear Filters

Replace values in each column by 0 after a pre-specified search value was found in that column

1 view (last 30 days)
Hello, i have a matrix A, for example A = [1, 1; 0.5, 1; 0.5, 0.5; 1, 1] I want to insert 0 values in each column, but only if a search value (e.g. 0.5) was found in that column. If the search value was found in the column, the remaining values in the column must be overridden by the value 0. I want to do this without implementing a for or while loop. So the result would be f(A) = [1, 1; 0.5, 1; 0, 0.5, 0, 0]
Can anyone help me create a function for this? thanks very much! Steven

Answers (2)

Stephen23
Stephen23 on 28 May 2018
Edited: Stephen23 on 28 May 2018
As requested, without any loop is easy in just one line of code:
>> A = [1, 1; 0.5, 1; 0.5, 0.5; 1, 1]
A =
1.0 1.0
0.5 1.0
0.5 0.5
1.0 1.0
>> A(cumsum(cumsum(A==0.5,1),1)>1) = 0
A =
1.0 1.0
0.5 1.0
0.0 0.5
0.0 0.0
You can easily put this into an anonymous function:
>> fun = @(M) M .* ~(cumsum(cumsum(M==0.5,1),1)>1);
>> fun(A)
ans =
1.00000 1.00000
0.50000 1.00000
0.00000 0.50000
0.00000 0.00000
Note: two cumsum calls are required to allow for one 0.5 value in a column.

jonas
jonas on 27 May 2018
Edited: jonas on 27 May 2018
Here is one solution,
[row,col]=find(A==0.5)
A(min(row(col==1))+1:end,1)=0
A(min(row(col==2))+1:end,2)=0
it may require a for loop for data sets with many columns tho..
  2 Comments
Steven Niggebrugge
Steven Niggebrugge on 28 May 2018
Hi, thanks for this. Indeed, a loop is still required. Can you explain me what the role is of the min() function in line 2 and 3? It looks like without the min() the function delivers the exact same results. thanks
jonas
jonas on 28 May 2018
You already got a better answer from Stephen, but the min() is required to return only the first row in each column where you have your 0.5. I'm surprised it works without the min(), but you are right.

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!