select columns from one matrix according to values in a second matrix

Hi, I'm trying to teach myself matlab by converting some code I originally wrote in R. The idea is to select columns from one matrix using values stored in another matrix and average them together.
I think the code below should work but I'm not sure how to handle the NaN values. In R I could use a which() statement but I'm not sure how to address this in matlab.
Any advice (or more elegant solutions)?
Thanks tom
x=magic(4)
y=[1 NaN NaN;2 3 4; 5 NaN NaN] %artificial example but rows need to be different lengths
out=zeros(size(x,1),size(y,1))
for i=1:size(y,1)
out(:,i)=mean(x(:,y(i,:)))

댓글 수: 1

Perhaps you could show the expected result for the above, since the code probably does not do what you want.

댓글을 달려면 로그인하십시오.

답변 (2개)

Oleg Komarov
Oleg Komarov 2011년 5월 25일
That's the only way the averaging is consistent with the output matrix:
x = magic(5);
y = [1 NaN NaN
2 3 4
5 NaN NaN];
szY = size(y);
out = zeros(size(x,1),szY(1));
for i = 1:szY(1)
idx = y(i,:);
out(:,i) = mean(x(:,idx(~isnan(idx))),2);
end
EDIT
So, there's the accumarray alternative but also the arrayfun which is basically a hidden loop:
out2 = arrayfun(@(z) mean(x(:,y(z,~isnan(y(z,:)))),2), 1:size(y,1),'un',0);
[out2{:}]

댓글 수: 3

The use of the idx variable certainly make this more readable, I was wondering if there was a function similar to the apply() function in R that performs a function on all rows (or columns) of a matrix without using the for loop?
Look at the dimensional argument to mean (the 2 at the end).
@Tom: mean directly cannot be applied since you change the columns you select, one option is accumarray but you will need to build subs and vals which is not the most trivial thing here, considering that the loop would be IMHO the best solution in terms of performance (speed and memory) and readability.

댓글을 달려면 로그인하십시오.

doc isnan
Might be of some use.

댓글 수: 3

y(i,(not(isnan(y(i,:)))))
may be of some use, it's a supremely ugly statement however.
so
mean(x(:,y(i,~isnan(y(i,:))))
?
We'll be able to see the operation more easily if you show us the expected result and logic.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

태그

질문:

2011년 5월 25일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by