[英]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. 如果这很容易解决,请原谅我,但是,II在MATLAB中有一个包含距离值的上三角矩阵。 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个和第j个值有行标签和列标签(考虑到矩阵分别为每个对应的行和元素包含{i,j}个值)。 I want to create a text file which looks like this: 我想创建一个文本文件,如下所示:
Label-i val Label-j
where i and j are respective column labels. 其中i和j分别是列标签。 This is pretty straight forward using 2 for loops to iterate over all the elements. 使用2 for循环迭代所有元素非常简单。
[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. 我看到了可以使用的arrayfun和其他MATLAB函数,但是,在这种情况下,我不知道如何使用它们。 Thanks for the help. 谢谢您的帮助。
Meshgrid will give you all row x col combinations. Meshgrid将为您提供所有x列的组合。
[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. 如果使用带有“远值”的矩阵,则应该使用sparse
矩阵。 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: 文件test.txt
的输出将是:
(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.