putting the answer in a matrices

3 views (last 30 days)
fyza affandi
fyza affandi on 25 Feb 2019
Edited: Jan on 25 Feb 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 Comment
Image Analyst
Image Analyst on 25 Feb 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?

Sign in to comment.

Accepted Answer

Jan
Jan on 25 Feb 2019
Edited: Jan on 25 Feb 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

More Answers (1)

madhan ravi
madhan ravi on 25 Feb 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{:})

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!