simple problem
조회 수: 2 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
답변 (2개)
Naz
2011년 12월 8일
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).
댓글 수: 0
Walter Roberson
2011년 12월 8일
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));
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!