Row search and Column name output

Asked by James on 28 Jun 2012
Latest activity Commented on by James on 29 Jun 2012

Hi,

I have a matrix (e.g., below) which I want to filter based on row numbers, and then output column names matching the non-zero column elements.

 A = [1 0 -1 2 0 1;0 2 1 0 1 -2;1 0 0 2 1 1]#matrix
 B = [1 3]#rows 1 and 3 are rows for searching.
 struc.names = ['blue', 'red', 'green', 'amber', 'grey','yellow']# a structure of column names.

I want to write a program to using specific row numbers (e.g., rows 1 and 3 above) to find columns in the matrix with non zero elements for thes rows, and then ouput the corresponding column names.

example output:

row 1 has the following non-zero column elements:

blue green amber yellow

row 3 has the following non-zero column elements:

blue amber grey yellow

I started writing the code this way:

    required_rows = [1 3];
    #preallocate storage for result
    RESULT = zeros(size(A([1 3],:) ~== 0)
    #open file for wriing and Loop
    fid=fopen('file.txt','w');
    for i = 1:size(RESULT)
	RESULT = RESULT + (struc.names((A([1 3],:)))
    end;
    fprintf "row A(i,:) has the following non-zero column elements"
    fprintf (RESULT,'\n', fid);

NOTE: the number of rows may be in millions and memory may be a problem

Please help get this code to work. Thanks

James

0 Comments

James

Products

No products are associated with this question.

1 Answer

Answer by Walter Roberson on 28 Jun 2012
Edited by Walter Roberson on 28 Jun 2012
Accepted answer
    struc.names = {'blue', 'red', 'green', 'amber', 'grey','yellow'}
    required_rows = [1 3];
    % open file for writing, and Loop
    fid=fopen('file.txt','wt');
    for K = 1 : length(required_rows);
      idx = A(required_rows(K),:) ~= 0;
      if any(idx)
        fprintf(fid, 'row A(%d,:) has the following non-zero column elements:\n');
        fprintf(fid, '%s ', struc.names{idx} );
        fprintf(fid, '\n');
      end
    end
    fclose(fid);

5 Comments

James on 29 Jun 2012

Thanks once again, Walter. Now I got the folllwoing output:

row A(blue green amber yellow

row A(blue amber grey yellow

INSTEAD OF:

example output:

row 1 has the following non-zero column elements:

blue green amber yellow

row 3 has the following non-zero column elements:

blue amber grey yellow

Best wishes,

James

Walter Roberson on 29 Jun 2012

fprintf(fid, 'row %d has the following non-zero column elements:\n', required_rows(K));

James on 29 Jun 2012

It works now! Walter, I'm grateful for your help. Thank you.

Walter Roberson

Contact us