Replace values in each column by 0 after a pre-specified search value was found in that column
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (2)
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.
0 Comments
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
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.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!