Replace values in each column by 0 after a pre-specified search value was found in that column
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
Stephen23
el 28 de Mayo de 2018
Editada: Stephen23
el 28 de Mayo de 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 comentarios
jonas
el 27 de Mayo de 2018
Editada: jonas
el 27 de Mayo de 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 comentarios
jonas
el 28 de Mayo de 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.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!