For loop and adding elements to an array. How to?

I have some function y(x). I would like to generate a list of y values for x between -10^-3 and 10^-3 in 10^-4 intervals and plot y vs x. I'm trying to do something simpler and less messy first for practice:
function test
global x
for n = -5; n < 5; n+1;
x(end+1)=2*n;
end
end
but this leaves me with x = -10. Why? What am I doing wrong and how could I fix it? Also, is there a way to make an array of x AND their corresponding y values simultaneously and then just plot that one thing? Like list = {{1,1},{2,4},{3,6},{4,8}} and plot this as pairs of coordinates.

5 件のコメント

per isakson
per isakson 2015 年 5 月 21 日
Re &nbsp for n = -5; n < 5; n+1; &nbsp see help on for
Solarmew
Solarmew 2015 年 5 月 21 日
編集済み: Solarmew 2015 年 5 月 21 日
i did, but i still can't figure out what I'm doing wrong
edit: oh, i guess for n=-5:1:5 works ... :I ... man ... 2015a help file is friggin useless ... might as well just google everything =___=
per isakson
per isakson 2015 年 5 月 21 日
"I guess for n=-5:1:5 works" &nbsp Did you try it?
Solarmew
Solarmew 2015 年 5 月 21 日
Yep. Watched a similar example of YouTube. Just realized that the help file I was looking at was for C ... why is there help for C in MatLab? +.+ ... that's the third time already that I try to use some syntax from the help file only to realize that it's not for MatLab ... dafuq ...
Walter Roberson
Walter Roberson 2015 年 5 月 21 日
Where did you find that help file?

サインインしてコメントする。

 採用された回答

Stephen23
Stephen23 2015 年 5 月 21 日
編集済み: Stephen23 2015 年 5 月 21 日

0 投票

MATLAB is not C or any other low-level programming language that requires loops to solve everything. In MATLAB the standard method is to generate the whole vector at once using the colon operator:
>> x = -10^-3:10^-4:10^-3
x = -0.001 -0.0009 -0.0008 -0.0007 -0.0006 -0.0005 -0.0004 -0.0003 -0.0002 -0.0001 0 0.0001 0.0002 0.0003 0.0004 0.0005 0.0006 0.0007 0.0008 0.0009 0.001
This is faster and neater than using loops: knowing how to write vectorized code makes using MATLAB a lot faster, productive and enjoyable!

その他の回答 (0 件)

カテゴリ

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

質問済み:

2015 年 5 月 21 日

編集済み:

2015 年 5 月 21 日

Community Treasure Hunt

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

Start Hunting!

Translated by