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

7 ビュー (過去 30 日間)
Wei-Chien Hu
Wei-Chien Hu 2018 年 8 月 28 日
コメント済み: Wei-Chien Hu 2018 年 8 月 28 日
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
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
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:
  2 件のコメント
Wei-Chien Hu
Wei-Chien Hu 2018 年 8 月 28 日
Thank you for solving my problem.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by