MATLAB Answers

How to extract diagonal elements of multiple nxn square matrix and place them in single mat file or matrix?

16 ビュー (過去 30 日間)
Sunny
Sunny 2018 年 9 月 27 日
編集済み: Sunny 2018 年 10 月 21 日
Hello,
I have 500 mat files with 10x10 double dimension. I want to extract the 10 diagonal elements from each matrix and place them in a single matrix which will be 500x10 (500 rows and 10 columns) each row consists of diagonal elements of one matrix. How can I make a single variable with all the diagonal elements?
Thanks
  6 件のコメント
Sunny
Sunny 2018 年 9 月 28 日
Thanks @Stephen. Yes, I used ytzhak answer for this issue and accepted his answer

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

採用された回答

ytzhak goussha
ytzhak goussha 2018 年 9 月 27 日
Hope this helps
step1:creat a nXnXm with random elements for the example:
%set dimensions of matrix
size_of_matrix=10;
number_of_matricides=500;
mat_input=randi(30,size_of_matrix,size_of_matrix,number_of_matricides);
step2: initialize an output matrix with nXm dimensions
mat_output=zeros(number_of_matricides,size_of_matrix);
step3: extract a diagonal from each matrix and place them in the output matrix
for i=1:number_of_matricides
mat_output(i,:)=diag(mat_input(:,:,i));
end
Alternatively, though not recommended, you can simply concatenate:
%initialize an empty matrix
mat_output=[];
for i=1:number_of_matricides
mat_output=[mat_output;diag(mat_input(:,:,i))'];
end
  5 件のコメント
Sunny
Sunny 2018 年 10 月 21 日
Thanks for the comment, I figured out that I need to create a struct with all the variables and access it. I already created a question and the link is New_Question

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

その他の回答 (0 件)

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by