How can I use 'strcat' and 'for loop' to read my Excel data?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Wei-Chien Hu
am 28 Aug. 2018
Kommentiert: Wei-Chien Hu
am 28 Aug. 2018
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 Kommentar
Stephen23
am 28 Aug. 2018
Bearbeitet: Stephen23
am 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.
Akzeptierte Antwort
KL
am 28 Aug. 2018
Bearbeitet: KL
am 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:
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Spreadsheets finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!