function y = spar(x, realFlag) % spar -- Convert array to "spar" form. % spar(x) returns a matrix whose rows list the indices % and complex values of the non-zero elements of array x. % The real and imaginary components are placed in separate % columns. Trailing rows or columns of zeros are ignored. % See "help unspar" for the inverse conversion. % spar(x, realFlag) delivers only the real-component of x, % if realFlag is TRUE; no column for the imaginary-component % is returned. % Copyright (C) 1999 Dr. Charles R. Denham, ZYDECO. % All Rights Reserved. % Disclosure without explicit written consent from the % copyright owner does not constitute publication. % Version of 19-Aug-1999 14:10:59. % Updated 24-Aug-1999 11:34:47. if nargin < 1, help(mfilename), return, end if nargin < 2, realFlag = 0; end siz = size(x); dim = length(siz); ind = find(x); sub = cell(1, dim); [sub{:}] = ind2sub(siz, ind); if ~realFlag result = zeros(length(ind), dim+2); else result = zeros(length(ind), dim+1); end for j = 1:dim result(:, j) = sub{j}; end if ~realFlag result(:, end-1) = real(x(ind)); result(:, end) = imag(x(ind)); else result(:, end) = real(x(ind)); end if nargout > 0 y = result; else disp(result) assignin('caller', 'ans', result) end