How can I use a string input in a "for" loop to get a matrix of names?

1 回表示 (過去 30 日間)
Sina Keshavarz
Sina Keshavarz 2017 年 2 月 1 日
コメント済み: Zhigang 2017 年 2 月 3 日
for i=0:2
a(i)=input('enter your name?','s')
end
what's wrong with this code? Matlab cannot read names I give to it. and here is the error: "Subscript indices must either be real positive integers or logicals."
  2 件のコメント
Stephen23
Stephen23 2017 年 2 月 1 日
Note: the original question used an if:
if i=0:2
a(i)=input('enter your name?','s')
end
Zhigang
Zhigang 2017 年 2 月 3 日
i should be started from 1. for i = 1:6 ....

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

回答 (2 件)

Alexandra Harkai
Alexandra Harkai 2017 年 2 月 1 日
The problem with this code is that (in MATLAB) indexing is from 1, not 0. Therefore a(0) is giving you the error.
As for the for loop (not if), if you want 3 inputs:
for i=1:3
a(i)=input('enter your name?','s');
end
  1 件のコメント
Star Strider
Star Strider 2017 年 2 月 1 日
That’s not the only problem. For any name longer than one letter, it will throw a
Subscripted assignment dimension mismatch.
error.
You have to use a cell array (notice the curly brackets ‘{}’ designating it as a cell array):
for i=1:3
a{i}=input('enter your name?','s');
end
Note: In all answers and comments, please test your code before posting it if at all possible. If you cannot, always label it as ‘untested code’.

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


Stephen23
Stephen23 2017 年 2 月 1 日
編集済み: Stephen23 2017 年 2 月 1 日
Your code has multiple mistakes: MATLAB indexing starts from one, you need to use a for loops, and you need to use a cell array:
N = 3;
C = cell(1,N);
for k = 1:N
C{k} = input('enter your name: ','s');
end
You should do the introductory tutorials, because they teach these very basic MATLAB concepts:
And also read this:

カテゴリ

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