필터 지우기
필터 지우기

How to convert a matrix to a structure array?

조회 수: 92 (최근 30일)
Hannah
Hannah 2018년 7월 18일
댓글: Hannah 2018년 7월 19일
I am working with data that is in a matrix but would like to easily convert it to a structure array. At the moment I am using the "table" and "table2struct" commands as per the simple example below but I feel that there should be a more efficient method that I'm missing as I will likely have far more than three variables and the current method I'm using seems inefficient. Any assistance would be appreciated!
M=randn(5,3);
T=table(M(:,1),M(:,2),M(:,3),'VariableNames',{'Var1' 'Var2' 'Var3'});
S=table2struct(T);
  댓글 수: 2
Steven Lord
Steven Lord 2018년 7월 18일
Why do you need to convert the matrix into a struct array? How are you planning to use the fields in the struct later in your code?
Personally most of the time I'd just leave it as M and use indexing to extract the columns as I need them.
Hannah
Hannah 2018년 7월 19일
I normally work with the data as M as you suggest but I would like to transform the data to a struct array as it is more rigorous in terms ensuring that there is no confusion about which variable is which when making data publically accessible.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 7월 19일
I'm with Steven, it would make more sense to keep it as is, or if the columns indeed represent different things, to change it to a table. A simpler version of your conversion would be:
T = array2table(M, 'VariableNames', compose('Var%d', 1:size(M, 2)))
tables are a lot more flexible than structures as you can access data by row or by column. With a structure you're putting the emphasis on the columns at the expense of rows.
If you really want a structure, then, for a matrix with an arbitrary number of column:
S = cell2struct(num2cell(M, 1), compose('Var%d', 1:size(M, 2)), 2)
  댓글 수: 1
Hannah
Hannah 2018년 7월 19일
Thanks Guillame. I'll give a table a go.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by