MATLAB: Dlmwrite help – including column and row numbers in output

column numbersdlmwriteMATLABrow numbers

Greetings,
I am using dlmwrite along with 'delimiter','\r' to export matrix data to individual lines in a txt. Is it possible to also include both the data's original matrix column number and row number on the same line as the data? Essentially producing 3 columns per line in the output txt file. The location in the original matrix is very important, and I would like to report this somehow in an easily readable format.
Thank you.

Best Answer

One way....
[i,j]=ind2sub(size(A),1:numel(A)); % the index vectors
B=A.'; % row major order 'cuz can't write A(:).'
>> fmt=[repmat('%3d,',1,2) '%3d\n']
fmt =
%3d,%3d,%3d\n
>> fprintf(fmt,[i' j' B(:)].')
1, 1, 1
2, 1, 2
3, 1, 3
1, 2, 4
2, 2, 5
3, 2, 6
1, 3, 7
2, 3, 8
3, 3, 9
>>
Let's see about dlmwrite; I don't use it much...
>> dlmwrite('test.txt',[i' j' B(:)],'delimiter',',','precision','%3d')
>> type test.txt
1, 1, 1
2, 1, 2
3, 1, 3
1, 2, 4
2, 2, 5
3, 2, 6
1, 3, 7
2, 3, 8
3, 3, 9
OK, that's ok, too...
BTW, my A was
A=reshape(1:9,3,3).';
just a little different than your example.