Filter löschen
Filter löschen

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

3 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Matt Fig
Matt Fig am 21 Nov. 2012
Bearbeitet: Matt Fig am 21 Nov. 2012
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).

Weitere Antworten (1)

Nigel
Nigel am 23 Nov. 2012
Bearbeitet: Nigel am 23 Nov. 2012
thank you! it worked out well! I have more questions to ask later though :)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by