For loop with variable

4 ビュー (過去 30 日間)
andrea vivas
andrea vivas 2021 年 4 月 22 日
コメント済み: DGM 2021 年 4 月 22 日
Hi I'm trying to build a for loop with variables only however it is not working it only gives me one correct value and then the other two are incorrect. The only one correct is the one where it says answer Idk what to do to make the other two work.
  1 件のコメント
Scott MacKenzie
Scott MacKenzie 2021 年 4 月 22 日
Why are you trying to use a for-loop? What you are trying to do?

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

回答 (2 件)

Cris LaPierre
Cris LaPierre 2021 年 4 月 22 日
Ch 13 of MATLAB Onramp covers for loops.
  2 件のコメント
andrea vivas
andrea vivas 2021 年 4 月 22 日
Yeah it still doesnt help me because they only use vectors with numbers and I'm trying to do it with variables.
Cris LaPierre
Cris LaPierre 2021 年 4 月 22 日
You might have to do a little application of what you learn.

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


DGM
DGM 2021 年 4 月 22 日
If you do this:
for n=1,2,3
% do thing
end
It's the same as doing
for n=1
2 % these do nothing but print to console
3
% do thing
end
Your loop will cycle only once. Instead, use
for n=[1 2 3]
because that actually specifies a vector.
Lastly, your loop doesn't actually store any values. It just dumps the result to console. If you intend to use it for something, you'll have to assign the output to a variable.
  2 件のコメント
andrea vivas
andrea vivas 2021 年 4 月 22 日
Perfect this solve it, and how do you assing the output to a variable?
DGM
DGM 2021 年 4 月 22 日
Consider the slightly more elaborate example:
inputvector=[12 564 32 9 6.2]; % specify inputs
outputvector=zeros(size(inputvector)); % preallocate outputs
for n=1:numel(inputvector) % define iterator based on input length
outputvector(n)=inputvector(n)/4; % store the output
end
Of course, if all you're doing is dividing by four and nothing else, this entire example can be simplified to:
inputvector=[12 564 32 9 6.2];
outputvector=inputvector/4;
Nothing in the loop is dependent on prior results, so you don't need it.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by