Save a vector from a loop 0:1
Mostrar comentarios más antiguos
I have this loop but i want to save the answers as a loop, how is it done? I have preallocated vectors before the loop and it works if i make the loop from 1:10 but i need to check for z = [0:1] with an steplength of 0.1
for z=[0:0.1:1]
y1real(z)= exp(z)*cos(z)
y2real(z)=-exp(z)*sin(z)
end
The loop works if I dont save y1real and y2real in vectors but i see the iterations in the command window
Thank you/Oskar
Respuestas (4)
Guillaume
el 16 de Jun. de 2016
obviously, you can't use decimal values as indices, so you would have to use an integer index both to iterate over your 0:0.1:1 array and over your destination array.
Even better, is to simply not use a loop:
z = 0:0.01:1;
y1real = exp(z) .* cos(z);
y2real = exp(z) .* sin(z);
Simply put those values in a vector, and iterate over the indices of that vector:
vec = 0:0.1:1;
y1real = NaN(size(vec));
y2real = NaN(size(vec));
for k = 1:numel(vec)
z = vec(k);
y1real(k) = +exp(z)*cos(z);
y2real(k) = -exp(z)*sin(z);
end
Of course with your example it is not required to use a loop at all, because MATLAB calculates on complete vectors all at once (this is called code vectorization):
vec = 0:0.1:1;
y1real = +exp(vec).*cos(vec);
y2real = -exp(vec).*sin(vec);
KSSV
el 16 de Jun. de 2016
z = [0:0.1:1] ;
y1 = zeros(size(z)) ;
y2 = zeros(size(z)) ;
for i = 1:length(z)
y1(i)= exp(z(i))*cos(z(i)) ;
y2(i)=-exp(z(i))*sin(z(i)) ;
end
KSSV
el 16 de Jun. de 2016
z = [0:0.1:1] ;
Y1 = exp(z).*cos(z) ;
Y2 = -exp(z).*sin(z) ;
without loop..
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!