MATLAB Answers

0

Help with learning indexing

Asked by Hilary Gaiser on 23 Apr 2019
Latest activity Edited by James Tursa
on 23 Apr 2019
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

Sign in to comment.

1 Answer

Answer by James Tursa
on 23 Apr 2019
Edited by 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

Ok, thanks! But why isn't it -4? I am thinking that if
x(2,end)
ans =
-4
and
x(1,end)
ans =
3
Why doesn't x(2,(end-1)/2) mean x(2, (-4 - 1)/2)?
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.

Sign in to comment.