perform calculation using for loop

1 回表示 (過去 30 日間)
Adam Kevin Francis Baker
Adam Kevin Francis Baker 2019 年 2 月 17 日
コメント済み: Walter Roberson 2019 年 2 月 18 日
So I have to use a for loop because I'm a student and the teacher said so. I've been trying to figure this one out and I'm sure theres a simple solution but because we are using matlab there aren't a whole lot of tutorials on using for loops when array operations are so much better.
I need to calculate the specific humidity using a for loop.
The equation is: q = (E*e)/P
where E = 0.622, e is a 96x144 matrix and, P represents p1 in my code which is another 96x144 matrix
I've coded something but I feel like the for loop is too simple.
Also the for loop and array operation return different values...is this normal?
% use for loop to calculate specific humidity
for q = 1:numel(p1)
q_for = (0.622.*e)./(p1(q));
end
% calculate specific humidity using array operations
q_array = (0.622.*e)./p1;
  2 件のコメント
Walter Roberson
Walter Roberson 2019 年 2 月 17 日
Your output in your for loop should probably be going into a variable indexed at something.
Adam Kevin Francis Baker
Adam Kevin Francis Baker 2019 年 2 月 17 日
q_for is the variable and i'm not sure what you mean by indexed at something...I thought thats what p1(q) was doing.

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

採用された回答

Adam Kevin Francis Baker
Adam Kevin Francis Baker 2019 年 2 月 18 日
Ok I had to do a double for loop to make it work because I was dealing with a matrix so I ended up writing this code to solve my problem:
for q = 1:length(p1)
for p = 1:min(size(p1))
q_for(p,q) = (0.622.*e(p,q))./(p1(p,q));
end
end
The array operation was simple:
q_array = (e.*0.622)./p1;

その他の回答 (1 件)

Adam Kevin Francis Baker
Adam Kevin Francis Baker 2019 年 2 月 18 日
This is what I did...
for q = 1:numel(p1)
q_for(q) = (0.622.*e(q))./(p1(q));
end
and for the array operation
q_array = (e.*0.622)./p1;
  2 件のコメント
Adam Kevin Francis Baker
Adam Kevin Francis Baker 2019 年 2 月 18 日
Still not quite right...the for loop is producing a 1x13824 array instead of a 96x144 array.
Walter Roberson
Walter Roberson 2019 年 2 月 18 日
That would have been okay under one of two circumstances:
  1. You pre-initialized q_for to be size(p1); or
  2. You reshaped vector q_for to be size(p1)

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by