Loop through hundreds of matrices to change values larger than 1 to 0
Show older comments
I have more than 400 matrices, currently I am using "find" to change the values larger than 1 in the matrix to 0 one by one manually with this code:
val = find(yf > 1);
yf(val) = 0;
Is there a way to do it with loop? Please help, thank you.
3 Comments
Walter Roberson
on 19 Oct 2017
Could you confirm that you want values between 0 and 1 exactly to be left alone? If the rule were that positive values were to be replaced by 0 then the operation is a bit more efficient.
James Tursa
on 19 Oct 2017
"... 400 matrices ..."
How are these matrices stored? In individual variables? As part of a cell or struct array? Or ...?
Zoe
on 19 Oct 2017
Accepted Answer
More Answers (2)
Star Strider
on 19 Oct 2017
Instead of find, I would simply use ‘logical indexing’.
Example —
yf = 0.5 + rand(4,5)
yf(yf > 1) = 0
yf =
0.64115 1.2321 1.0209 1.3162 1.1876
1.0121 1.2498 0.71908 1.2939 1.4869
1.2213 0.90732 1.3424 0.96911 1.2699
1.4288 0.73949 1.1629 0.80952 1.3296
yf =
0.64115 0 0 0 0
0 0 0.71908 0 0
0 0.90732 0 0.96911 0
0 0.73949 0 0.80952 0
This should be more efficient, although you will still have to loop through every matrix.
2 Comments
Zoe
on 19 Oct 2017
Star Strider
on 19 Oct 2017
That depends on how your matrices are stored. If each is in a separate file, read the file and then do the replacement.
James Tursa
on 19 Oct 2017
result = cellfun(@(c)c.*(c<=1),images,'uni',false);
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!