我正在研究一个Matlab程序,该程序创建2n *n矩阵,其中n和矩阵的每个项(这些只是0或1)是键盘输入值。其思想是,在最后打印位置i,j,其中矩阵的项为1。
例如,如果矩阵A的输入为:
array = [];
array2 = [];
arrayb = [];
arrayb2 = [];
for m = 1: n
for n = 1: n
if A(m,n)==1;
array = [array, m];
array2 = [array2, n];
end
if B(m,n)==1;
arrayb = [arrayb, m];
arrayb2 = [arrayb2, n];
end
end
end
fprintf(array,array2)
输出应该是
(1,1) = 1
(1,2) = 1
(2,1) = 0
(2,2) = 1
我只能单独提取每个术语索引
{(1,1) ,(1,2), (2,2)}
您可以使用find()
查找所有非零值。使用~A
来反转布尔值并找到后面的零。然后将所有内容连接起来,使用fprintf()
打印。
A = rand(3)>0.5; % Random sample data
[row, col, val] = find(A); % Find 1s
labels = [row.';col.';val.']; % concatenate for printing
fprintf('(%d, %d) = %dn',labels) % print
[row, col, val] = find(~A); % Find 0s
val(:) = 0; % We know it should be 0
labels = [row.';col.';val.']; % concatenate for printing
fprintf('(%d, %d) = %dn',labels) % print
% Output
A =
1 1 1
1 1 1
0 0 1
(1, 1) = 1
(2, 1) = 1
(1, 2) = 1
(2, 2) = 1
(1, 3) = 1
(2, 3) = 1
(3, 3) = 1
(3, 1) = 0
(3, 2) = 0
或者,如果您只是想打印所有值及其索引,我们可以利用meshgrid()
快速组装索引,然后在打印之前再次展开和连接:
A = rand(3); % Random sample data
[col, row] = meshgrid(1:size(A,2), 1:size(A,1));
labels = [row(:).';col(:).';A(:).']; % concatenate for printing
% Change the printing spec for the value to something relevant
fprintf('(%d, %d) = %0.4fn',labels) % print
A =
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
(1, 1) = 0.8147
(2, 1) = 0.9058
(3, 1) = 0.1270
(1, 2) = 0.9134
(2, 2) = 0.6324
(3, 2) = 0.0975
(1, 3) = 0.2785
(2, 3) = 0.5469
(3, 3) = 0.9575