Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
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

Réponses (2)

Stephen23
Stephen23 le 28 Mai 2018
Modifié(e) : Stephen23 le 28 Mai 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 le 27 Mai 2018
Modifié(e) : jonas le 27 Mai 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 commentaires
Steven Niggebrugge
Steven Niggebrugge le 28 Mai 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 le 28 Mai 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Produits


Version

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by