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

3 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by