# simple problem

5 views (last 30 days)
August edwards on 8 Dec 2011
I'm quite new to all this, and I have a very simple problem. Okay, so what I have is a 5x2-matrix with data. I want to define a function b(i) that takes the i'th element in the 2nd column. I've tried different things with the for-loop, but I don't think I'm doing it right. I wrote(where a is my matrix):
for i=1:5
b(i)=a(i,2)
end
but b(i) becomes a row vector with b(1)...b(5) adding up and when you ask for b(i) i just returns the value in the last row. So a problem is clearly also that, matlab doesn't see i as a variable in the way I want it to. What can I do?

Naz on 8 Dec 2011
Your code is correct: the 'for' loop makes a copy of the first column of matrix a. Is it that what you wanted to do? You have to realize that the variable b is not defined, so when you write b(i) it automatically creates a variable b of length i. Usually, if you know the size of your feature matrix, you should preallocate the space. For example, if you know that your b will end up being matrix 5x1, then it would be grammatically correct to write
b=zeros(5,1);
this should save calculation time (for large matrices). Currently your variable 'b' is rewritten each loop (the row becomes longer by one element each loop). If you just want to read a specific element from the matrix 'a', just do b=a(3,2); which will give you the element of the third row, second column. The reason you get a value of the last row when you call for b(i), is because after the loop is finished, the value of 'i' is 5, and thus you call for b(5).

Walter Roberson on 8 Dec 2011
b = @(i) a(i,2);
b will then be a function (not an array) that will return the 2nd column of the i'th row of a as it existed at the time b was defined (it will not change as you change a).
If you want to defined b as a function that works with the current a, updating as a changes, then that requires some semi-magic code:
b = @(i) subsref( evalin(caller, 'a'), struct('type','()','subs',i));