简体   繁体   中英

Printing MATLAB Elements using loop

I'm using MATLAB to print a 3x3 matrix [2,3,4;5,7,8;1,4], Now how can I use loop to print the boundary element of the matrix. So (7) should not be printed in the output as per the below

 2     3     4
 5           8
 1     4     3

This works for matrices of any size . The matrix should not contain NaN . The result has automatic column spacing .

Matrix = [2 3 4 9; 5 7 8 4; 1 4 3 0]; % input
M = Matrix;                           % make a copy. Will be overwritten
M(2:end-1, 2:end-1) = NaN;            % set inner entries to NaN
c = num2str(M);                       % convert to char array. Provides column alignment
c = cellstr(c);                       % convert to cell array of char row vectors
c = strrep(c, 'NaN', '   ');          % replace 'NaN' in each char row vector by spaces
c = cell2mat(c);                      % convert back to char array
disp(c)                               % display

This example produces the display

2    3    4    9
5              4
1    4    3    0

As another example (to see the automatic column spacing),

Matrix = [1237123 5 72347; 23486234862 234234 9172364; 5 777 33];

produces

    1237123            5        72347
23486234862                   9172364
          5          777           33

Convert your matrix to a categorical matrix and replace all inner entries to a figure-space as shown below:

M = [2,3,4; 5,7,8; 1,4,3]; %given sample-input matrix
C = categorical(M); %converting to a categorical matrix
C(2:end-1, 2:end-1) = char(8199); %setting inner entries to a figure-space
disp(C); %displaying resultant values of C

and the result is:

2      3      4 
5             8 
1      4      3 

A solution that uses a for-loop and that omits the inner numbers from being printed can be done by using a set of nested for-loops to traverse through the rows and columns. If you only need this to work for the 3 by 3 case you can change the if condition to: if(Row == 2 && Column == 2) . The if-statement checks to ensure that the element does not fall within the borders:


Element is not on the border if the following conditions are all true:

Row does not equal 1
Column does not equal 1
Row does not equal Number_Of_Rows
Column does not equal Number_Of_Columns

Matrix = [2 3 4; 5 7 8; 1 4 3];

[Number_Of_Rows,Number_Of_Columns] = size(Matrix);

for Row = 1: Number_Of_Rows
    for Column = 1: Number_Of_Columns
    
    Value = Matrix(Row,Column);
    if (Row ~= 1 && Column ~= 1 && Row ~= Number_Of_Rows && Column ~= Number_Of_Columns)
        fprintf("    ",Value);
    else        
        fprintf("%d   ",Value);
    end
  
    end
    fprintf("\n");
end

Ran using MATLAB R2019b

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