Jack Salah
Jack Salah

Reputation: 25

Using XLS read in MATLAB and a forloop

I am trying to save some data from MATLAB to excel.

This is very repetitive and I was hoping to use a for loop to significantly reduce the number of lines of code I am using.

To give an example:

APPLES = rand(1,10);
PEARS = rand(1,10);
Horizon = (1:10);
% Writing to excel 
xlswrite('Results.xlsx',APPLES,'Apple','B2')
xlswrite('Results.xlsx',Horizon,'Apple','B1')

%Pears
xlswrite('Results.xlsx',PEARS,'Pear','B2')
xlswrite('Results.xlsx',Horizon,'Pear','B1')

The above code will create an excel sheet called Results with two worksheets Apple and Pear with the data I need.

Is it possible to create a for loop to reduce the number of code, as I am actually using 200 fruits, so it starting to take up a lot of space and time to write them by hand?

I have tried to do it by hand which is time-consuming and I have also tried this method which doesn't work:

%test

Apples = rand(1,10);
Pears = rand(1,10);
Horizon = (1:10);

names1 = {'Apples' 'Pears'};
%%
for ii = 1:length(names1)
% Writing to excel 
xlswrite('Results22.xlsx',fprintf(names1{ii}),names1{ii},'B2')
xlswrite('Results22.xlsx',Horizon,names1{ii},'B1')
end

Upvotes: 0

Views: 68

Answers (1)

Adiel
Adiel

Reputation: 3071

The problem is that inside the loop you call the string that represents the name of the variable, instead of the variable itself.

For example, fprintf(names1{ii}) gives the string 'Apples', instead of the variable Apples, that contain the values.

To resolve that, and for good practice of not holding 200 fruits in workspace, you can define the fruits as fields of struct. Then, you can access it with dynamic field name:

fruit_names = {'Apples', 'Pears'};
Horizon = (1:10);

for k=1:length(fruit_names)
   fruit.(fruit_names{k}) = rand(1,10);
   xlswrite('Results22.xlsx',fruit.(fruit_names{k}),fruit_names{k},'B2')
   xlswrite('Results22.xlsx',Horizon,fruit_names{k},'B1')
end

Upvotes: 2

Related Questions