find the last non-zero column in matrix in pre-allocated matrix

5 ビュー (過去 30 日間)
Mahsa
Mahsa 2014 年 10 月 16 日
回答済み: Mahsa 2015 年 3 月 27 日
Hello, My matlab code is creating very very matrix and I didn't pre-allocate it before. Because I always need to know the size of matrix. However, due to memory problem I had to make a very large zero matrix and fill in the matrix with new value. Any my question is to how to find the last non-zero column in that matrix "in the most efficient way". for exam if I have a matrix M = zeros(10^9,6) and there is some value like the follwign matrix how to find row 6 as the answer. Thank you,
M= [3388 3279 3284 3383 3279 3278; 3388 3383 2043 2038 2038 0; 3387 3388 2038 2037 2032 2037; 3388 3389 3384 3383 2038 0; 3388 3279 3280 3389 3274 3279; 0 0 0 0 0 0; 0 0 0 0 0 0]

採用された回答

Mohammad Abouali
Mohammad Abouali 2014 年 10 月 16 日
編集済み: Mohammad Abouali 2014 年 10 月 16 日
1) if you are looking for las non-zero column why the answer to your example is row 6?
2) if you are looking for last non-zero row, shouldn't the answer to your example be 5? in that case find(any(M,2),1,'last') would give 5 as the answer

その他の回答 (3 件)

Geoff Hayes
Geoff Hayes 2014 年 10 月 16 日
編集済み: Geoff Hayes 2014 年 10 月 16 日
Mahsa - try using the any function to determine which rows have at least one non-zero element as
nzRows = any(M,2);
nzRows will be a vector of ones and zeros where a one indicates that the row has at least one non-zero element, and a zero indicates that all elements in the row are all zero. The use find to find the last element in nzRows that is a one. Type doc find for details on how to use this function.

Mahsa
Mahsa 2015 年 3 月 27 日
another way is to delete the zeros
if m = [ 1 2 3 4 5 0 0 0 0 0 0 0 0] m(m==0)=[] m= [1 2 3 4 5];
However my question is what to do if zero is one of the real values like the following example:
m = [ 1 2 0 3 4 0 5 0 0 0 0 0 0 0 0];
I'm looking for a command that gives me
m = [ 1 2 0 3 4 0 5]
Thank you

Mahsa
Mahsa 2015 年 3 月 27 日
Oh I see it can be answered by find(any(M,1),1,'last')

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by