Row search and Column name output

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

 Accepted Answer

Walter Roberson
Walter Roberson on 28 Jun 2012
Edited: Walter Roberson on 28 Jun 2012
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

Thanks for your help, Walter. I tried running the amended code but it hangs and there was not output in the file. I use 64bit windows.
Sorry I was missing an "end" so it was waiting for the statement to be completed. I edited the code above.
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
fprintf(fid, 'row %d has the following non-zero column elements:\n', required_rows(K));
It works now! Walter, I'm grateful for your help. Thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!