How can I use 'strcat' and 'for loop' to read my Excel data?

3 views (last 30 days)
Hello, my Excel data name is "b1,b2...b40", and i want to write a code with for loop to read Excel.
for example:
b1 = xlsread('b1.csv'); %read my Excel data [2048*2]
r1 = [b1(:,2)./cal(:,2)]; %calculate my data
b1(:,2) = r1; %cover my original data
%%%%%%%%%%%%%%%%%%%%%%%%%%
I want to use "for loop" to run all my data (40), but it didn't work.
this is my code:
for i=1:40
strcat('b',num2str(i)) = xlsread(strcat('b',num2str(i),'.csv'));
strcat('r',num2str(i))= [strcat('b',num2str(i),'(:,2)') ./ cal(:,2)];
strcat('b',num2str(i),'(:,2)') =strcat('r',num2str(i));
end
Matlab usually said"Subscripted assignment dimension mismatch.", but I don't know how to fix it.
Plz help me, or recommend me, thank you everyone.
  1 Comment
Stephen23
Stephen23 on 28 Aug 2018
Edited: Stephen23 on 28 Aug 2018
Do NOT dynamically name variables! Dynamically naming variables is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
Much simpler and more efficient is to use indexing, exactly as the MATLAB documentation shows:
Please upload a sample data file by clicking the paperclip button.

Sign in to comment.

Accepted Answer

KL
KL on 28 Aug 2018
Edited: KL on 28 Aug 2018
There are better ways to handle multiple files in MATLAB. But the main problem in your attempt is that you're not only trying to create file names to use inside xlsread but you're also trying to create dynamic variables (on the LHS of your xlsread line). That's really bad.
Here are some tips. Use dir to get the list of files on your current folder and you can use this in your for loop. For example,
%execute line by line and see what you get in the workspace
folderInfo = dir('*.csv'); %get the file names and stuff
fileNames = {folderInfo.name}; %extract the file names
for fCount = 1:numel(fileNames)
temp_b = xlsread(fileNames{fCount});
%do your stuff -->r1 = [b1(:,2)./cal(:,2)]; and here b1 is temp_b
...
end
you don't need dynamic variables. If you want to write the new data into the file, use xlswrite or csvwrite.
Goodluck!
Links:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!