MATLAB: Row search and Column name output

matrixmatrix manipulation

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

Best 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);