putting the answer in a matrices

3 ビュー (過去 30 日間)
fyza affandi
fyza affandi 2019 年 2 月 25 日
編集済み: Jan 2019 年 2 月 25 日
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 件のコメント
Image Analyst
Image Analyst 2019 年 2 月 25 日
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?

サインインしてコメントする。

採用された回答

Jan
Jan 2019 年 2 月 25 日
編集済み: Jan 2019 年 2 月 25 日
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

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 2 月 25 日
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 件のコメント
madhan ravi
madhan ravi 2019 年 2 月 25 日
To remove rows with all zeros:
Result(sum(Result,2)~=0,:)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by