How can I use 'strcat' and 'for loop' to read my Excel data?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-8-28
编辑:Stephen23
2018-8-28
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.
采纳的回答
KL
2018-8-28
编辑:KL
2018-8-28
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:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!