Error using table.init (line 401) The VariableNames property must contain one name for each variable in the table.
9 views (last 30 days)
Show older comments
Hi
I am trying to save the variables in the form of .xls table but it gives the following error:
Error using table.init (line 401)
The VariableNames property must contain one name for each variable in the table.
This is the code:
for subject=1:2
for ii=1:2
resultFileName = sprintf('Sub%i_S%i_NN.mat',subject,ii); % generate result filename
load(resultFileName)
Accuracy_NN(subject,ii) = acc;
A = array2table(Accuracy_NN,'VariableNames',{'NN_S1','NN_S2'});
Accuracy_NN_e(subject,ii) = acc_e;
B = array2table(Accuracy_NN_e,'VariableNames',{'NN_Epoch_S1','NN_Epoch_S2'});
%
Total=[A B];
%
%
writetable(Total,'xyz.xlsx','Sheet',1,'Range','A1')
end
end
Any idea how to resolve it.?
1 Comment
Answers (1)
Guillaume
on 24 Mar 2020
"Any idea how to resolve it.?"
Well, yes provide as many variable names as there are columns in the arrays Accuracy_NN and Accuracy_NN_e.
Unfortunately, since your code has no comment and it never show these arrays being created we can't tell what their size is. Possibly, the variable doesn't exist before your loops start in which case it grows inside the loop (bad design! See Preallocation)
However, there is clearly something not right with your loops. Your loops fill the arrays element by element. At each step, while you haven't finished filling the arrays you attempt to convert them to a table and export them to a file. Most likely the conversiona and export is meant to happen after the loops.
While we're at it another issue is that you're using load to pop variables into the workspace. That's dangerous, if your mat file contains variables you didn't expect they may overwrite your current variables. Always assign the output of load to a variable.
So I suspect your code is meant to be:
numsubjects = 2;
numii = 2; %better variable name than ii required!
%preallocate arrays. Don't grow them in the loop.
Accuracy_NN = zeros(numsubjects, numii);
Accuracy_NN_2 = zeros(numsubjects, numii);
%fill the arrays
for subject=1:2
for ii=1:2
resultFileName = sprintf('Sub%i_S%i_NN.mat',subject,ii);
result = load(resultFileName); %I presume that the mat file contains variables acc and acc_e
Accuracy_NN(subject,ii) = result.acc;
Accuracy_NN_e(subject,ii) = result.acc_e;
end
end
%convert to table and export
Total = array2table([Accuracy_NN, Accuracy_NN_e], 'VariableNames', {'NN_S1', 'NN_S2', 'NN_Epoch_S1', 'NN_Epoch_S2'});
writetable(Total,'xyz.xlsx','Sheet',1,'Range','A1')
Personally, I'd preallocate the 2x4 Total table before the loop and fill that in the loop without bothering at all with the 2 temporary arrays.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!