Why doesn't this command work (vector addition)?
1 回表示 (過去 30 日間)
古いコメントを表示
for x=1:0.5:10
y(x) = x + 1
end
Why doesn't this above command work, but the one below does? What is it about the "0.5" that prevents this from running? X is still a vector in both of these commands, so what's wrong here?
for x=1:10
y(x) = x + 1
end
Why is it that I need a counting variable, as shown below, for the first command above to work?
x=1:0.5:10
for i=1:length(x)
y(i) = x( i ) + 1
end
0 件のコメント
回答 (2 件)
Jan
2018 年 2 月 4 日
編集済み: Jan
2018 年 2 月 4 日
Did you read the error message?
for x = 1:0.5:10
y(x) = x + 1
end
produces:
Subscript indices must either be real positive integers or logicals.
This hits the point already. In the expression y(x) the x is the index related to the array y. It means: set the x.th element of the variable y to the value x + 1 . But if x is 1.5, Matlab is instructed to address the 1.5-th element and this is not possible for trivial reasons. There is only a 1st and a 2nd element, but no element between them.
Do you know Excel? A vector is like a column there. You have elements with the address "A1" and "A2", but no "A1.5".
The "counting variable" solves this problem easily: Now the indices are positive integers and not directly related to the used values.
By the way, an efficient solution does not need a loop here:
x = 1:0.5:10;
y = x + 1;
2 件のコメント
Stephen23
2018 年 2 月 5 日
編集済み: Stephen23
2018 年 2 月 5 日
"is this correct? "
Yes, your understanding is correct.
Note that in MATLAB the "entry/grid position" of any vector (or matrix) is called an element, so the loop index i specifies the first element, the second element, etc. The term element applies to matrices, vectors, and arrays, so use it when referring to an "entry/grid position" and we will always understand each other :)
You might like to read this too:
Star Strider
2018 年 2 月 4 日
You are defining ‘y’ as a vector. In MATLAB, subscripts are defined as integers greater than zero.
So this will not work because the subscripts are not integers:
for x=1:0.5:10
y(x) = x + 1
end
while this one will because they are:
for x=1:10
y(x) = x + 1
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!