Home > front end >  Is it possible to print matrix in MATLAB?
Is it possible to print matrix in MATLAB?

Time:08-30

I have this very simple function which takes an integer as input, generates two random matrices and multiplies them before printing the time it takes.

function [] = mymatrix(n)
mat1 = randi([0 100], n, n);
mat2 = randi([0 100], n, n);
tic
result = mymult(mat1, mat2);
disp("First matrix:")
disp(mat1) 
disp("Second matrix:")
disp(mat2)
disp("Multiplied:")
disp(result);
toc
end

The program works, and I get this output:

>> mymatrix(2)
Elapsed time is 0.000614 seconds.
First matrix:
    34    10
    77    87

Second matrix:
    11    31
    30    81

Multiplied:
         674        1864
        3457        9434

Elapsed time is 0.002148 seconds.

But I was wondering if it is possible to write the display lines more compact?

Something like this: fprintf("Calculated: \r", X) but for matrices? Because when I try to write fprintf("First matrix: " mat1), like so:

function [] = mymatrix(n)
mat1 = randi([0 100], n, n);
mat2 = randi([0 100], n, n);
tic
result = mymult(mat1, mat2);
fprintf("First matrix: "   mat1)
%disp(mat1) 
disp("Second matrix:")
disp(mat2)
disp("Multiplied:")
disp(result);
toc
end

I get an error:

>> mymatrix(2)
Error using fprintf
Invalid file identifier.  Use fopen to generate a valid file identifier.

CodePudding user response:

Normally you can combine variables' values into strings/chars using sprintf or fprintf, which allow format specifiers for how the variable should be formatted in the string. However, you will have issues trying to use printf commands for matrix inputs, because they try to expand inputs of different sizes.

Example for n=2

>> fprintf( 'First matrix: \n%d', mat1 )
First matrix: 
82First matrix: 
80First matrix: 
65First matrix: 
38

The easiest one-liner in this case is probably to just abuse cellfun a bit instead, which will loop over its inputs and call any function, in this case disp:

cellfun( @disp, {'First matrix:', mat1, 'Second matrix:', mat2, 'Multiplied:', result} );

This gives you exactly the same output as before, because it's doing literally the same thing (calling disp on your 6 inputs).

First matrix:
    88    62
    55    59
Second matrix:
    20    47
    30    23
Multiplied:
        3620        5562
        2870        3942

I'm not sure this is any better than the original 6-line option, sure it's now a one liner but it's also arguably reduced your code readability.

  • Related