Borrar filtros
Borrar filtros

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

3 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Matt Fig
Matt Fig el 21 de Nov. de 2012
Editada: Matt Fig el 21 de Nov. de 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).

Más respuestas (1)

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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by