putting the answer in a matrices

9 vues (au cours des 30 derniers jours)
fyza affandi
fyza affandi le 25 Fév 2019
Modifié(e) : Jan le 25 Fév 2019
I have matrix a. Then, I find which column in each row has number bigger than 1. The code is as below
a =
5 0 0 0 0 0 0 0 0 0
3 1 0 0 0 0 0 0 0 0
1 2 0 0 0 0 0 0 0 0
1 0 1 0 0 0 0 0 0 0
>> for cpart=1:size(a,1)
b=a(cpart,:);
row = find(b ~=0)
end
row =
1
row =
1 2
row =
1 2
row =
1 3
How can I put the row in a matrices ?(as shown below)
row = [1 0
1 2
1 2
1 3]
  1 commentaire
Image Analyst
Image Analyst le 25 Fév 2019
What are you going to do if you have row? Because I'm thinking you don't even need it and whatever you're going to do can be done much easier with a mask
mask = a~=0; % Create a logical 2-D matrix.
So I don't want to tell you how to get row if it just makes things more complicated for what you eventually want to do. So, what will you do with row if you had it?

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 25 Fév 2019
Modifié(e) : Jan le 25 Fév 2019
With a loop:
nA = (a ~= 0);
nRow = size(a, 1);
nCol = max(sum(nA, 2));
result = zeros(nRow, nCol); % Pre-allocation
for c = 1:nRow
v = find(nA(c, :));
result(c, 1:numel(v)) = v;
end

Plus de réponses (1)

madhan ravi
madhan ravi le 25 Fév 2019
b=arrayfun(@(x)find(a(x,:)),1:size(a,1),'un',0);
M=max(cellfun('prodofsize',b));
C=cellfun(@(x)[x zeros(1,M-numel(x))],b,'un',0);
Result=vertcat(C{:})
  1 commentaire
madhan ravi
madhan ravi le 25 Fév 2019
To remove rows with all zeros:
Result(sum(Result,2)~=0,:)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices 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