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

回答 (4 件)

Guillaume
Guillaume 2016 年 6 月 16 日

1 投票

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);
Note the use of .* for elementwise multiplication
Stephen23
Stephen23 2016 年 6 月 16 日
編集済み: Stephen23 2016 年 6 月 16 日

0 投票

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
KSSV 2016 年 6 月 16 日

0 投票

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
KSSV 2016 年 6 月 16 日

0 投票

z = [0:0.1:1] ;
Y1 = exp(z).*cos(z) ;
Y2 = -exp(z).*sin(z) ;
without loop..

カテゴリ

ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索

タグ

質問済み:

2016 年 6 月 16 日

編集済み:

2016 年 6 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by