Why doesn't this command work (vector addition)?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Jan
am 4 Feb. 2018
Bearbeitet: Jan
am 4 Feb. 2018
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 Kommentare
Stephen23
am 5 Feb. 2018
Bearbeitet: Stephen23
am 5 Feb. 2018
"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
am 4 Feb. 2018
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 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!