Run a loop through multiple matrices

6 ビュー (過去 30 日間)
Navneet
Navneet 2014 年 1 月 15 日
コメント済み: Navneet 2014 年 1 月 16 日
Hi, I have 15 matrices, say A1, A2 and so on.. I want to remove all the values below 0.10 and above 0.30 from all of these matrices. Then, I want to replace all of those places with NaN. Can someone please help me with this?
This might be basic, but I am very new to matlab or any kind of coding. Thanks! NK

採用された回答

Kelly Kearney
Kelly Kearney 2014 年 1 月 16 日
編集済み: Kelly Kearney 2014 年 1 月 16 日
To do the replacement on a single variable, you just need
x(x < 0.1 | x > 0.3) = NaN;
To apply it to all your variables, there are a few possibilities.
- Type that line 15 times, replacing x with whatever the names of your 15 variables are.
- If the variables are named systematically, as you suggested (i.e. A1, A2, A3), you could try using eval, as Amit suggests. But eval is usually recommended against, because it can cause unexpected outcomes if you're not careful (and it makes for very ugly code).
- My suggestion: just create a function that applies the NaN-replacement to any number of variables.
function varargout = addnans(varargin)
for ii = 1:length(varargin)
varargout{ii} = varargin{ii};
varargout{ii}(varargout{ii} < 0.1 | varargout{ii} > 0.3) = NaN;
end
Then you could call it as
[A1, A2, ...] = addnans(A1, A2, ...)
This will work regardless of the number of variables, or whether the variables follow a systematic naming convention or not. Just make sure your input variables always match your output variables.
  1 件のコメント
Navneet
Navneet 2014 年 1 月 16 日
Hi Kelly, That worked! Thank you so much.
NK

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

その他の回答 (1 件)

Amit
Amit 2014 年 1 月 16 日
Something like this:
for i = 1:5
eval(['A' num2str(i) '(' 'A' num2str(i) '<0.1 | A' num2str(i) '>0.3)' '=' 'NaN'])
end
  2 件のコメント
Navneet
Navneet 2014 年 1 月 16 日
Hi Amit, Thank you for the response. Can you please explain why you chose i=1:5? Also, I actually have different names for all these matrices, so how will the loop run through all of them? Thanks!
Navneet
Navneet 2014 年 1 月 16 日
And, those names are not in the series like I had given in the example. Sorry about that!

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by