Save multiple columns of multiple csv files?
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi,
I have the following code:
[file_list, path_n] = uigetfile('.csv', 'Grab csv', 'Multiselect', 'on')
columns();
if ismatrix(file_list) == 0
file_list = {file_list}
end
for i = 1:length(file_list)
filename = file_list{i}
data_in = readmatrix([path_n, filename]);
% here I would like to import columns 7-27 for each file
% but instead of saving only the last iteration of the loop I want to
% save each in a new variable
columns(i) = data_in(:,7:27);
end
Every time I run this I get an error that I dont understand.
Unable to perform assignment because the left and right sides have a different number of elements.
Error in test (line 10)
columns(i) = data_in(:,7:27);
I have figured out how to get the 21 columns saved in columns but it only saves the last iteration. How do I save each iteration?
Help would be much appreciated.
댓글 수: 1
Stephen23
2022년 1월 21일
Simpler way to ensure that the output is a cell array of character vectors:
[file_list, path_n] = uigetfile(...);
file_list = cellstr(file_list); % <- easy
채택된 답변
Voss
2022년 1월 21일
[file_list, path_n] = uigetfile('.csv', 'Grab csv', 'Multiselect', 'on');
if ~iscell(file_list)
file_list = {file_list};
end
columns = cell(length(file_list),1);
for i = 1:length(file_list)
filename = file_list{i};
data_in = readmatrix([path_n, filename]);
columns{i} = data_in(:,7:27);
end
% if you want to put all the data into one matrix:
columns = cell2mat(columns);
댓글 수: 3
Voss
2022년 1월 21일
That's correct: as written, they will all end up in a single matrix. But if you remove the line:
columns = cell2mat(columns);
then they'll be in a cell array where each cell contains a matrix from one file. You can access each file's data like:
columns{1}
columns{2}
columns{end}
% etc.
If all the matrices had the same size, you could put them in a 3D array instead, but a cell array of matrices of different sizes is preferable to multiple matrix variables called column_1, column_2, etc., in MATLAB. Basically, you shouldn't do the column_1, column_2 thing, and here is why: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!