Info
This question is closed. Reopen it to edit or answer.
Help with learning indexing
1 view (last 30 days)
Show older comments
I am just learning how to index and I can't understand why the following produces the answer that it does. I would expect it to not work as is would produce an integer not withing the range of indices of the array. Could someone please explain why this works and what the column portion is referencing? Thanks!
x = [ 1 2 3; 3.4 pi -4]
x =
1.0000 2.0000 3.0000
3.4000 3.1416 -4.0000
x(2,(end-1)/2)
ans =
3.4000
0 Comments
Answers (1)
James Tursa
on 23 Apr 2019
Edited: James Tursa
on 23 Apr 2019
x is size 2x3, so the 'end' in the 2nd index position is 3. Then just do the math
(3-1)/2 = 2/2 = 1
so x(2,(end-1)/2) = x(2,1) = 3.4
2 Comments
James Tursa
on 23 Apr 2019
Edited: James Tursa
on 23 Apr 2019
Again, the 'end' when used inside of indexing is specifically the dimension and is not related in any way to the value of the variable at that spot. So, in those cases you just replace 'end' with the current dimension of that particular index spot. An 'end' in the first indexing spot above would be replaced with 2, an 'end' in the second indexing spot above would be replaced with 3. The fact that the value of x(1,3) is 3 and is the same as the second dimension of 3 is just coincidental and is fooling you.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!