フィルターのクリア

What is the correct way to use arrays with function inside for loop?

3 ビュー (過去 30 日間)
Nigel
Nigel 2012 年 11 月 21 日
function [ z ] = z_funct( x,y )
z=0.0817.*(3.71.*sqrt(x)-0.25.*x+5.81).*(y-91.4)+91.4;
end
x=[1 2 3 4 5];
y=[-20:2:40];
for i=1:5
z(i)=z_funct(x(i),y);
end
z
What I actually want to do is to calculate z, when x vary, but y stays the same
This operation returns error: In an assignment A(I) = B, the number of elements in B and I must be the same.
I know it is something wrong with my array dimensions, but I can't figure it out.

採用された回答

Matt Fig
Matt Fig 2012 年 11 月 21 日
編集済み: Matt Fig 2012 年 11 月 21 日
If you want to hold y as a vector, then for every x(i) in the loop your function call will return a vector. You cannot store a vector in a single numeric array element. Use a cell array instead:
z_funct = @(x,y) 0.0817*(3.71*sqrt(x)-0.25*x+5.81)*(y-91.4)+91.4
x=[1 2 3 4 5];
y=-20:2:40;
for ii=1:length(x)
z{ii} = z_funct(x(ii),y);
end
Now z is a cell array.
z{1} has z_funct(1,-20:2:40)
z{2} has z_funct(2,-20:2:40)
z{3} has z_funct(3,-20:2:40)
etc.
.
.
.
.
You could also make an array with those values:
for ii=1:length(x)
z2(ii,:) = z_funct(x(ii),y);
end
Now z2 is an array with row 1 being z_funt(1,-20:2:40).

その他の回答 (1 件)

Nigel
Nigel 2012 年 11 月 23 日
編集済み: Nigel 2012 年 11 月 23 日
thank you! it worked out well! I have more questions to ask later though :)

カテゴリ

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