Provide a Matlab code to print Diagonal elements in a matrix

2 ビュー (過去 30 日間)
Surya Kumar
Surya Kumar 2023 年 3 月 1 日
コメント済み: Surya Kumar 2023 年 3 月 1 日
In a given n*n matrix we have to traverse each row and print diagonal elements of each row.
For example m = [4 5 6;7 8 9;10 11 12] , expected answer is :
4
5 7
6 8 10
It would of great help if Code is provided.

採用された回答

Adithya
Adithya 2023 年 3 月 1 日
Below is the code to print diagonal elements of each row:
m = [4 5 6;7 8 9;10 11 12];
n = size(m,1);
for i=1:n
k=1;
for j=1:i
fprintf('%d ',m(k,i-j+1))
k=k+1;
end
disp(' ');
end
% output:
% 4
% 5 7
% 6 8 10
Logic : first loop ie i=1:n is to traverse row wise in a matrix m and second loop is to print the diagonal elements in a matrix also if we are in first row we have to print one element ,in second row 2 elements is to be printed and in ith row i elements have to be printed, disp function is used to move to new line after printing diagonal elements of previous row.
  1 件のコメント
Surya Kumar
Surya Kumar 2023 年 3 月 1 日
Thank you , the code itself is self explainatory

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by