: Indexing with NaN, and python zip function in matlab

4 vues (au cours des 30 derniers jours)
Jakub Matousek
Jakub Matousek le 29 Sep 2017
Réponse apportée : Rik le 2 Nov 2017
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?

Réponse acceptée

Rik
Rik le 2 Nov 2017
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]

Plus de réponses (0)

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by