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

조회 수: 9 (최근 30일)
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
Stephen23
Stephen23 2018년 9월 28일
@Varun Mandalapu: note that concatenating onto the output array is not very efficient. For a more efficient solution you should preallocate the output array and use indexing, as ytzhak goussha's answer shows.
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
Guillaume
Guillaume 2018년 10월 21일
@yzthak,
Just reread your answer in more details, and I noticed something that made me chuckle:
You may want to read the definition of matricide. I believe you meant matrices
Sunny
Sunny 2018년 10월 21일
편집: 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개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by