How to append matrix row depending on index in for loop?

1 回表示 (過去 30 日間)
Mike Rovan
Mike Rovan 2019 年 9 月 27 日
コメント済み: Matt J 2019 年 9 月 27 日
I have a 3D array of size 512 512 100 of ones and zeros. I want to look at the rows and record any row that contains all zeros in a new array, and stops when it comes across a row that contains a single one. However, I want to record the rows in a new 100 512 matrix where each row in that matrrix contains the index numbers of all the rows containing zeros in the original array. I wrote a small script but the recording in the new array part doesnt work:
Array=single.empty(100,0);
for 3Dimages=1:100
for i=1:512*inputofuser
if Original3Dimage(i,:,3Dimages)==0
Array(3Dimages,:)=[Array(3Dimages,:),i];
else
break
end
end
end
so it should be that each each row in the new 'Array' contains the index numbers for the rows containing zeros in the original array for that page number from 1:100
so there would be 100 rows, each one being for the 1:100 3Dimages number
and each row would have different number of columns, 512 being the greatest(maybe) beause each 3Dimages number would have a different number of rows containing zeros. Therefore there would be some empty cells (column-wise). If this is not possible, is there a different way to record the index numbers, seperating each of the 100 pages.

採用された回答

Matt J
Matt J 2019 年 9 月 27 日
編集済み: Matt J 2019 年 9 月 27 日
Array=squeeze(~any(Original3DArray,2)).';
This is a little different than what you asked for, but I claim that it's better. The result will be a 100x512 logical array such that Array(i,j)=1 if the i-th 3D image has all zeros in the j-th row and 0 otherwise. Remember that in Matlab, logical vectors can be used to index just as well as numeric indices can. And, the whole thing is one line of well-vectorized code.
If you really must have the indices in numeric form (but why???) rather than in logical form then you can add these additional lines:
Array=num2cell( Array.*(1:size(Array,2)) ,2);
Array=cellfun(@nonzeros,Array,'uni',0);
This will give you a cell array such that Array{i} contain the indices for the i-th image.
  3 件のコメント
Mike Rovan
Mike Rovan 2019 年 9 月 27 日
this wouldnt work for my code purpose. I was hoping to have a list of indexes seperated by the 3Dimages pages so that they may be used in future code. A logical array would not work.
Matt J
Matt J 2019 年 9 月 27 日
But even if that's the case, I showed you the additional code needed to get the list of indices.
Array=num2cell( Array.*(1:size(Array,2)) ,2);
Array=cellfun(@nonzeros,Array,'uni',0);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by