Hi, I have a 3d tensor in MATLAB. Call it A. Lets say, size(A)=[4 6 10]. I have another matrix M which holds few indexes of the first two dimensions of the matrix A. Like
M=[1 5;3 2;1 4];
Now, I want to set all elements of the matrix A as zero which has the different index (of the first two dimensions) than the matrix M. Basically, what I want to do is-
A((if index(A{1,2})~=M),:)=0
Please help me.

 Akzeptierte Antwort

the cyclist
the cyclist am 31 Jul. 2017

0 Stimmen

This is a little clunky, but it works.
A = rand(4,6,10);
M = [1 5;
3 2;
1 4;];
[a1,a2,a3] = size(A);
[m1,m2] = size(M);
subIndices = [repmat(M,a3,1),repmat((1:a3)',m1,1)];
linearIndicesToKeep = sub2ind([a1,a2,a3],subIndices(:,1),subIndices(:,2),subIndices(:,3));
linearIndicesToZero = setxor(linearIndicesToKeep,1:(a1*a2*a3));
A(linearIndicesToZero) = 0;

3 Kommentare

Souvik Agasti
Souvik Agasti am 31 Jul. 2017
Bearbeitet: Souvik Agasti am 14 Aug. 2017
Hi 'the cyclist',
Thanks a lot. But, I would like to make some change over it.
A = rand(4,6,10);
M = [1 5; 3 2; 1 4;];
[a1,a2,a3] = size(A);
[m1,m2] = size(M);
dimen3 = repmat((1:a3),m1,1);
subIndices = [repmat(M,a3,1), dimen3(:)];
linearIndicesToKeep = sub2ind([a1,a2,a3],subIndices(:,1),subIndices(:,2),subIndices(:,3));
linearIndicesToZero = setxor(linearIndicesToKeep,1:(a1*a2*a3));
A(linearIndicesToZero) = 0;
Jan
Jan am 14 Aug. 2017
@Cyclist: What a pitty that there is no direct solution like:
B(M(:,1), M(:,2), :) = A(M(:,1), M(:,2), :)
This copies the rectangular sub-matrices but not the desired pages.
Instead of the XORing, I'd copy the wanted elements only:
B = zeros(size(A));
B(linearIndicesToKeep) = A(linearIndicesToKeep);
the cyclist
the cyclist am 14 Aug. 2017
@Jan: That direct solution is so logical that I tried it first.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by