Reputation: 69
Pardon me if this is easily solvable, but, I I have a upper-triangular matrix in MATLAB containing distance values. Suppose there are row labels and column labels for each i-th and j-th value respectively (considering the matrix contain {i,j} values for each corresponding row and elements, respectively). I want to create a text file which looks like this:
Label-i val Label-j
where i and j are respective column labels. This is pretty straight forward using 2 for loops to iterate over all the elements.
[r,~] = size(A);
mat = [];
for i = 1:r
for j = 1:r
tmpmat = [collabels(i) A(i,j) rowlabels(j)];
mat = [mat;tmpmat];
end
end
But, I want to know what faster ways exist to do the same. I saw similar posts in the forum before, but, not exactly pertaining to this. If anybody can give me some insight on this, it'd be great. I saw arrayfun and other MATLAB functions which can be used, but, I couldn't figure out how to use them in this case. Thanks for the help.
Upvotes: 2
Views: 711
Reputation: 6715
One way to do it without loop is:
A = randi(100, 2, 3);
collabels = [0, 1, 2];
rowlabels = [3, 4];
[m, n] = size(A);
B = repmat(collabels, m, 1);
B = B(:)';
C = repmat(rowlabels, 1, n);
tmpmat = [B; A(:)' ; C];
mat = tmpmat(:);
Output:
A =
14 11 50
73 66 78
mat =
0 14 3
0 73 4
1 11 3
1 66 4
2 50 3
2 78 4
Upvotes: 1
Reputation: 4308
Meshgrid will give you all row x col combinations.
[XX,YY] = meshgrid(collabels,rowlabels);
mat = [XX(:) A(:) YY(:)];
Upvotes: 3
Reputation: 4650
If you are using a matrix with "distant values" you should be using a sparse
matrix. Evaluation of a sparse matrix will give you the coordinates and values directly, so I would suggest just saving the output directly into a file. Here's an example:
% Create sparse matrix
A = sparse(10,10);
A(5,5) = 1;
A(2,2) = 1;
% Save the disp() output into a string
A_str = evalc('disp(A)');
% Write this string to a file
fid = fopen('test.txt', 'wt');
fprintf(fid,'%s',A_str);
The output in the file test.txt
will be:
(2,2) 1
(5,5) 1
Upvotes: 2