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

1 vue (au cours des 30 derniers jours)
Nigel
Nigel le 21 Nov 2012
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.

Réponse acceptée

Matt Fig
Matt Fig le 21 Nov 2012
Modifié(e) : Matt Fig le 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).

Plus de réponses (1)

Nigel
Nigel le 23 Nov 2012
Modifié(e) : Nigel le 23 Nov 2012
thank you! it worked out well! I have more questions to ask later though :)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by