Reputation: 909
For example, I have the matrix:
A = [1 3 5;
2 7 3;
9 3 8];
I want to remove the number 3
from matrix A
, thus obtaining a new matrix:
B = [1 5;
2 7;
9 8];
If I try to simply remove it with A=A(A~=3)
, it just gives me a column vector without number 3
, but I want a matrix with the exact changed size. Anyone has any idea how to do it?
Upvotes: 0
Views: 225
Reputation: 45741
Generic solution:
B = arrayfun(@(r)(A(r,A(r,:)~=3)), 1:size(A,1), 'Uni', false)'
which outputs a cell array and makes no assumptions about how many 3
s there are per row.
For illustration, I will rewrite the above line as a for-loop:
for r = 1:size(A,1)
row = A(r,:)
B(r) = row(row~=3)
end
If all your rows contain an equal number of 3s then see Santhan's answer
Or else according to your new requirements from the comments just:
A(A==3) = NaN;
or if you want to eliminate more than just one number
A(ismember(A, [2,3])) = NaN
Upvotes: 2
Reputation: 3898
One Alternate, assuming each row containing equal number of 3's
A = [1 3 5; 2 7 3; 9 3 8];
B = A.'; %//'
out = reshape(B(B~=3),[],size(A,1)).'
Results:
A =
1 3 5
2 7 3
9 3 8
out =
1 5
2 7
9 8
Note: If the number of 3's in each rows are not equal, see the Generic solution by @Dan in the other answer
Or here is other alternative using mat2cell
& cellfun
Code:
%// creating cells where each cell contain one row
AC = mat2cell(A,ones(1,size(A,1)),size(A,2));
%// returning only the elements not equal to 3 in each row
out = cellfun(@(x) x(x~=3),AC,'uni',0)
Results:
A =
1 3 5 3
2 7 3 1
9 3 8 5
out =
[1x2 double]
[1x3 double]
[1x3 double]
Upvotes: 2