Storing variables in for loop

6 ビュー (過去 30 日間)
Mary Jean Savitsky
Mary Jean Savitsky 2022 年 3 月 24 日
コメント済み: Stephen23 2022 年 3 月 24 日
Hello! I am trying to create a for loop to store 16 different .csv files. The issue I am running into is that the for loop is only saving the last .csv file (file 16). I understand that the for loop is overwriting the "forcedData" variable with every iteration but I've tried using:
forcedData(k) = csvread(fileName,3,0);
and
forcedData(:,k)= csvread(fileName,3,0);
But neither of these work due to the number of elements being different on each side. I am fairly new to MATLAB so if anyone knows how to fix this issue so that I may have 16 different data sets in the forcedData variable, please help! I have included my scipt so far below this line:
for k = 1:16
%importing csv files
if k <=16
fileName = sprintf('forced_%d.csv',k);
end
if isfile(fileName)
forcedData(:,k)= csvread(fileName,3,0);
else
fprintf('File %s does not exist.\n',fileName);
end
end
  1 件のコメント
Stephen23
Stephen23 2022 年 3 月 24 日

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

回答 (1 件)

KSSV
KSSV 2022 年 3 月 24 日
csvFiles = dir('*.csv') ;
N = length(csvFiles) ;
iwant = cell(N,1) ;
for i = 1:N
iwant{i} = csvread(csvFiles(i).name) ;
end

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by