A For Loop Question.

Given the vector x = [1 8 3 9 0 1], create a code that computes the sine of the given x-values. Here is the coding:
s = zeros(size(x));
for j = 1:length(x)
s(j) = sin(x(j));
end
I have only started learning for loops today, and I am confused about what the zeros(size(x)) is doing in the code, and what it's exactly doing to keep the code going.
Also, for
i=1;
while (i<=10)
disp(i);
i = i + 1;
end
What does i = i+1 do, how is it different to i = i -1 or i = i + 2?
Thanks for the help.

回答(2 个)

You do not need a for loop for this
x = [1 8 3 9 0 1];
sin(x)
In this:
i=1;
while (i<=10)
disp(i);
i = i + 1;
end
i starts as 1 and while i is less than or equal to 10, you're doing something. If you do not change i, then i will always be 1. You could increment by two i = i+2 if you wanted to.
You can get s simply by doing this:
s = sin(x);
Be aware that there is a sind() that takes arguments in degrees - that may come in handy sometimes.
For the second code, obviously you're either adding 1 to the loop index i, or subtracting 1 or adding 2. Who ever told you to do that forgot to exemplify the recommendation against using i and j (the imaginary variables) as loop indexes since they will override them. Use ii or k or loopIndex some other descriptive name instead. And for the i=i-1 case, your loop will never exit. This is called an infinite loop. You should put in some other kind of failsafes to prevent that, like checking if a loop counter is more than a million or whatever is way more than the number of times you ever expect to run your loop.
k = 0; % Loop index
loopCounter = 0; % Loop counter - counts # times loop is run.
while (k > -100) && (k <= 10) && (loopCounter < 1000000) % Check both ends of the range
disp(k);
k = k-2; % Change loop index.
loopCounter = loopCounter + 1; % Count number of loop iterations.
end
If you want to write bulletproof robust code you always have to anticipate ways things can go wrong and try to prevent or accomodate for that. Things like, using try/catch, using exist() to check for files before you access them, using fullfile(), checking if uint8 values might add together and then get clipped, that sort of thing.

此问题已关闭。

提问:

Tee
2012-5-26

关闭:

2021-8-20

Community Treasure Hunt

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

Start Hunting!

Translated by