Naming VariableNames in a table based on a cell array

I have an array data2 which is 1x576 and I have a cell array called data2_txt which is also 1x576. I have giving a small example below (the arrays im using are much larger)
data2=[1,5,3,5,6;1,2,4,12,6];
data2_txt={'Var1','Var2','Var3','Var4','Var5'}
Why do I get the error
Error using setVarNames (line 37)
The VariableNames property must contain one name for each variable in the table.
Error in table (line 305)
t = setVarNames(t,vnames); % error if invalid, duplicate, or empty"
When I use the following syntax
Table1=table(data2,'VariableNames',data2_txt);
I am able to get this to work if I use a loop. But given previous criticism of using loops vs vectorization in MatLab I am trying to avoid doing so to keep the code quick. Below is the code I can get working using a loop which is not very efficient
table3=table();
for i=1:length(data2)
table2a=table(data2(:,i),'VariableNames',data2_txt(i))
table3=horzcat(table3,table2a)
end
Any advice or direction would be greatly appreciated.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2016년 7월 6일
편집: Azzi Abdelmalek 2016년 7월 6일
data2=[1,5,3,5,6;1,2,4,12,6]
data2_txt={'Var1','Var2','Var3','Var4','Var5'}
Table1=cell2table(num2cell(data2),'VariableNames',data2_txt)
%Or
data2=[1,5,3,5,6;1,2,4,12,6]
data2_txt={'Var1','Var2','Var3','Var4','Var5'}
v=mat2cell(data2,size(data2,1),ones(1,size(data2,2)))
Table1=table(v{:},'VariableNames',data2_txt)

댓글 수: 5

This is exactly what I was looking for. Thank you very much!
Patrick
Patrick 2016년 7월 7일
편집: Patrick 2016년 7월 7일
Is there any reason the result would be different when using a larger matrix? I used the code on my larger array and cell (data3 and data3_txt in the image).
When I double click on the table it brings me into its properties. This doesn't happen with the data2 example. I used the Thoughts?
For large tables, matlab variable editor does not display the content anymore, just the properties of the table.
The content of the table is still the same.
As far as I know you cannot change that behaviour.
Thank you for the feedback Guillaume. Good thing to know for the future
There's no need to use cell arrays for this. Instead of converting to a cell array, use array2table, not the table constructor:
Table1=array2table(data2,'VariableNames',data2_txt);

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2016년 7월 6일

댓글:

2016년 8월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by