Home > Enterprise >  Print the pair i,j of a matrix whose value is 1 in matlab
Print the pair i,j of a matrix whose value is 1 in matlab

Time:05-26

I'm working on a Matlab program that creates 2 n*n matrices, where n and each of the terms of the matrix (these will just be 0 or 1) are keyboard input values. The idea is that at the end the positions i,j in which the terms of the matrix are 1 are printed.

For example, if the inputs of matrix A are:

    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)

The output should be

    (1,1) = 1
    (1,2) = 1
    (2,1) = 0
    (2,2) = 1

I have only been able to extract each of the term indices separately

    {(1,1) ,(1,2), (2,2)}

CodePudding user response:

You can use find() to find all non-zero values. use ~A to reverse the booleanness and find the zeros afterwards. Then concatenate everything and use fprintf() to print.

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) = %d\n',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) = %d\n',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

Or, in case you simply want to print all values with their indices, we can utilise meshgrid() to quickly assemble the indices and then again unravel and concatenate before printing:

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.4f\n',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
  • Related