: Indexing with NaN, and python zip function in matlab

Hi, I have matrices like this:
v = [4 10;20 8]
a = [1 2;2 2]
First problem is:
I want to do an operation simillar to this one:
b(:,1) = v(a(1,:),a(2,:))
Which yields :
b = [10 10;8 8]
But I would like it to function like a zip in python, so it should give me:
b = [10 8] or b = [10;8]
The second problem is some of the columns in the a matrix are NaNs so I cant index over them, I need to skip these in a way that I would get inf or NaNs in the matrix b... and I cant just delete these columns because I need the order and position of output stay the same. Is there any other way(better optimized for performance) than swapping NaNs for valid indexes and then go over output and change corresponding rows/columns back to NaNs?

 채택된 답변

Rik
Rik 2017년 11월 2일
v = [4 10;20 8];
a = [1 2;2 2];
index=(sub2ind(size(v),a(1,:),a(2,:)));
result=nan(size(index));
result(~isnan(index))=v(index(~isnan(index)));
%result=[10 8];
v = [4 10;20 8];
a = [1 2;NaN 2];
index=(sub2ind(size(v),a(1,:),a(2,:)));
result=nan(size(index));
result(~isnan(index))=v(index(~isnan(index)));
%result=[NaN 8]

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

질문:

2017년 9월 29일

답변:

Rik
2017년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by