简体   繁体   中英

finding the first non zero column in a matrix

if i have matrix A like the following

2 0 0 0 0 0 
3 0 0 0 0 0
4 0 0 0 0 0
7 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0 
0 0 0 0 0 0  

all the other columns are always zeros

I want to get the array B = [7 4 3 2]

how can i do that ?

Hey this is the easiest code i can think of for getting all non zero elements:

test_matrix = [ 2, 0 , 0 ,0 ,0;...
    3, 0 , 0 ,0 ,0;...
    4, 0 , 0 ,0 ,0;...
    7, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0];

B = test_matrix(test_matrix ~= 0) %//rowwise non zeroelements

The output is a column we need to transpose it and then flip it. If you change the position of 4 to another slot in the column it will show at the end of output array B. If you want to have the last non zero element as first output you can transpose the Array:

B=fliplr(B'); %//fliping first to last and so in ( for the transpose array)

If you want the column ordered even if as said above the 4 is somewhere else in the array use the transposed matrix:

helper= test_matrix' %//(')transposing Matrix
C = helper(helper ~=0) %//Columnwise non zero-elements

If there are more than one nonzero element per column you must check if you want them rowwise or columnwise listed: Check B and C definition. Obviously C isn't inverse ordered just use

 C=fliplr(C); %%//flipping first to last and so on

hopefully that explains all questions you got.
Results:

test_matrix = [ 2, 0 , 0 ,0 ,0;...
    3, 0 , 0 ,0 ,0;...
    0, 0 , 4 ,0 ,0;...
    7, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0;...
    0, 0 , 0 ,0 ,0];

helper= sum(test_matrix');
C = helper(helper ~=0);
B = test_matrix(test_matrix ~= 0);

Results in:

C= (7,4,3,2);
B= (4,7,3,2);

You can loop over the columns and use find . Let's take

M =
     0     0     1     0     0
     0     0     2     0     0
     0     0     3     0     0
     0     0     4     0     0
     0     0     0     0     0

as our example-matrix.

for i = 1:size(M,2)
    ind = find(M(:,i));
    if ind
        found = ind;
        break;
    end
end

Will get you

found = 
    1
    2
    3
    4

Which you can flip with

found = found([end:-1:1])'

which will get you

found =
    4 3 2 1

您的问题尚不清楚,但这似乎可以满足您的要求(因为所有其他列均为零):

flipud(nonzeros(A))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM