generating files using loop or other functions

I have the attached data and I want to create an excel sheet with name Test1 that includes the 1st column with the 2nd column, then to create another files with name Test2 that includes the 1st column with the 3rd column and so on assuming I have many columns. Thanks in advance.

2 comentarios

Stephen23
Stephen23 el 27 de Oct. de 2020
Editada: Stephen23 el 27 de Oct. de 2020
To future readers: the accepted answer uses inefficient, complex code to access the table variables.
Do NOT follow this bad code example!
My comment below the answer shows the simpler, neater, less buggy, easier to debug, and much more efficient approach (i.e. the one given in the MATLAB documentation). Do NOT learn bad ways of writing MATLAB code.
@Stephen, Thanks for your comment.

Iniciar sesión para comentar.

 Respuesta aceptada

Sudhakar Shinde
Sudhakar Shinde el 27 de Oct. de 2020
Use readtable and writetable functions.
Data=readtable('x1)Data.xlsx'); % Read excel data
[R,C]=size(Data); % get number of columns
VariableNames = Data.Properties.VariableNames; % Name of each column heading
for i=2:C
Out.Nu = eval(['Data.',VariableNames{1}]); % 1st column
Out.Var = eval(['Data.',VariableNames{i}]) ;
Table = table(Out.Nu,Out.Var);
writetable(Table,['Test' num2str(i-1),'.xlsx']); %%write into excel exmaple: Test1.xlsx
end

5 comentarios

Thanks a lot! that was exactly what I need.
Stephen23
Stephen23 el 27 de Oct. de 2020
Editada: Stephen23 el 27 de Oct. de 2020
Do NOT use eval to access table variables (or fieldnames, etc.) !
The correct approach is to use the syntax shown in the MATLAB documentation:
Data.(VariableNames{1})
Tip: if you are using eval for basic things like accessing data, then you are doing something wrong.
Sudhakar Shinde
Sudhakar Shinde el 27 de Oct. de 2020
Editada: Sudhakar Shinde el 27 de Oct. de 2020
@Stephen, Thanks for your comment. 'Data.(VariableNames{1})' is more efficient way.
@Abdulkarim, Please use easy way/syntax to access table data as:
Out.Nu = Data.(VariableNames{1});
Out.Var = Data.(VariableNames{i}) ;
instead of
Out.Nu = eval(['Data.',VariableNames{1}]); % 1st column
Out.Var = eval(['Data.',VariableNames{i}]) ;
I have used it and gave me the same answer. Thanks all.
Welcome.

Iniciar sesión para comentar.

Más respuestas (0)

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by