Why doesn't this command work (vector addition)?
6 次查看(过去 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 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!