Storing values in a vector using a loop

This is a simple version of what i'm trying to implement in a function:
d = zeros(1,N)
for i = 1:N
d(1,i)=input('Distance = ');
end
I thought I was storing the ith value in the vector, but when it saved to my workspace it came out as a scalar!?
How do I create a vector of values using a loop? Why is it not working?

4 件のコメント

Torsten
Torsten 2025 年 4 月 19 日
N = 3;
d = zeros(1,N)
for i = 1:N
d(1,i)=input('Distance = ');
end
d
This will prompt you three times to give a distance value - and after the loop, d will come out as 1x3 vector with elements being the input values you used.
Annie
Annie 2025 年 4 月 19 日
編集済み: Annie 2025 年 4 月 19 日
You're right. No clue why my functions not doing that and unfortunately I'm not able to give the code. Thanks for trying though.
Can you think of any reason why it's not working?
Edit: Is there a way to run a function line by line like a live script?
Matt J
Matt J 2025 年 4 月 20 日
移動済み: Matt J 2025 年 4 月 20 日
Note that there is no reason you need to do this with a loop. A vector can be entered with a single input statement, e.g.,
>> d=input("Distances = ")
Distances = [1,2,5,7]
d =
1 2 5 7
Annie
Annie 2025 年 4 月 20 日
編集済み: Annie 2025 年 4 月 20 日
Yes, I'm aware. However, this is not the only case for which I'm using this method. Anyway, I realized my error and it's fixed.
Thank you though

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

回答 (1 件)

Steven Lord
Steven Lord 2025 年 4 月 20 日

1 投票

Edit: Is there a way to run a function line by line like a live script?
Yes, the Debugger.

カテゴリ

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

質問済み:

2025 年 4 月 19 日

回答済み:

2025 年 4 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by