简体   繁体   中英

Accessing all elements of a matrix in MATLAB without using 'for' loops

Pardon me if this is easily solvable, but, II 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.

Meshgrid will give you all row x col combinations.

[XX,YY] = meshgrid(collabels,rowlabels);
mat = [XX(:) A(:) YY(:)];

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM