フィルターのクリア

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

1 回表示 (過去 30 日間)
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

回答 (2 件)

Stephen23
Stephen23 2018 年 5 月 28 日
編集済み: Stephen23 2018 年 5 月 28 日
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 2018 年 5 月 27 日
編集済み: jonas 2018 年 5 月 27 日
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 件のコメント
Steven Niggebrugge
Steven Niggebrugge 2018 年 5 月 28 日
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 2018 年 5 月 28 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by