Given the constraints, I only really see one sensible option for the given format:
f = fopen('out.txt', 'w');
for ii=1:size(mat, 1)
fprintf(f, '%u ', find(mat(ii, :));
fprintf(f, '\n');
end
fclose(f);
Since the number of elements per row isn't constant, this means two things:
- We can't construct a single matrix to pass to a vectorised function, so we're stuck with some form of per-row operation.
- We also can't give
fprintf
a constant format string to write one or more whole rows in a single call, so we're stuck with multiple fprintf
calls.
So, optimising for those constraints;
- Iterate over the rows directly - yes, we could pull out the row and column indices all at once with
find
, but then we've wasted memory effectively copying the entire dataset, and we'd still have to iterate over that somehow.
- Minimise the amount of high-level work - let the low-level internals of
find
and vectorised fprintf
at least make processing a single row as quick as feasibly possible.
Sometimes a simple loop really is the best option - it's liable to be I/O-bound anyway, so the overhead of the loop itself really should be negligible compared to even the minimal number of fprintf
calls.