Loop through hundreds of matrices to change values larger than 1 to 0

2 ビュー (過去 30 日間)
Zoe
Zoe 2017 年 10 月 19 日
コメント済み: Zoe 2017 年 10 月 23 日
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 件のコメント
James Tursa
James Tursa 2017 年 10 月 19 日
"... 400 matrices ..."
How are these matrices stored? In individual variables? As part of a cell or struct array? Or ...?
Zoe
Zoe 2017 年 10 月 19 日
Hi Walter, those matrices are actually image data, the value I WANT is actually between 0 and 1 (definitely smaller than 1), and values larger than 1 are noise (background data, etc.)
Hi James, in a 1*452 cell array , so I use
images{1, #}
to read them one by one right now.

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

採用された回答

Image Analyst
Image Analyst 2017 年 10 月 19 日
If you want a loop and your images are in the cell array, you can do it like this:
for k = 1 : length(images)
% Extract his one image.
thisImage = images{1, k};
% Reduce/Clip values 1.000001 and larger to 1.
thisImage(thisImage > 1) = 1;
% Stick back into cell array
images{1, k} = thisImage;
end
  3 件のコメント
Image Analyst
Image Analyst 2017 年 10 月 21 日
You're welcome, but you probably never should have stored all your images in a cell array in the first place. It takes up a lot of memory and there was probably never a need to have them all in memory simultaneously. You probably could have read your images one at a time and processed them immediately in the loop without storing them all. Anyway, thanks for Accepting the answer.
Zoe
Zoe 2017 年 10 月 23 日
Thank you for letting me know this:)

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

その他の回答 (2 件)

Star Strider
Star Strider 2017 年 10 月 19 日
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 件のコメント
Zoe
Zoe 2017 年 10 月 19 日
Thank you for replying! But my question is how are you gonna do the loop?? Sorry I am relatively new to matlab, and I do know lots of functions but I dont know how to loop through my matrices.
Star Strider
Star Strider 2017 年 10 月 19 日
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
James Tursa 2017 年 10 月 19 日
result = cellfun(@(c)c.*(c<=1),images,'uni',false);

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by