How to flatten and split and concatenate arrays in several files

조회 수: 24 (최근 30일)
Kong
Kong 2020년 3월 15일
댓글: Kong 2020년 3월 16일
Hello.
I want to flatten and split and concatenate arrays in several files.
For example,
I have several datasets (237 x 40, 238 x 40, 239 x 40 ....)
1. I want to flatten each dataset
(237 x 40 -> 1 x 9480 , 238 x 40 => 1 x 9520, 239 x 40 = > 1 x 9560)
2. I want to split each datasets to minimum length among datasets.
1 x 9480, 1 x 9480, 1 x 9480
3. concatenate (3 x 9480)
I can do as several codes, but I have lots of data.
So I want to reduce the code.
clear all
close all
X = csvread('boxing/boxing50.csv');
Y = csvread('boxing/boxing51.csv');
Z = csvread('boxing/boxing52.csv');
% flatten
X = reshape(X,[],1);
Y = reshape(Y,[],1);
Z = reshape(Z,[],1);
% find the minimum and split to the minimum length
X = X(:,1:9480)
Y = Y(:,1:9480)
Z = Z(:,1:9480)
% concatenate
All = [X; Y; Z]
  댓글 수: 1
Kong
Kong 2020년 3월 15일
Hello.
Before flattening each CSV file, I found that each file has a different size of the matrix.
(237 x 39 , 238 x 38 , 239 x 37 ...)
In other words, I want to find each minimum length of row and column and flatten them.
Before : 237 x 39 , 238 x 38 , 239 x 37 ...
After : 237 x 37 , 237 x 37 , 237 x 37 ...

댓글을 달려면 로그인하십시오.

채택된 답변

Akira Agata
Akira Agata 2020년 3월 15일
편집: Akira Agata 2020년 3월 15일
I think the following code can do that task:
By the way, your code will output 28440-by-1 (28440 = 9480 x 3), not the 3-by-9480. So the following code will generate N-by-1 array.
% Create the list of csv files
s = dir('boxing/*.csv');
% Read from each csv file
c = cell(numel(s),1);
for kk = 1:numel(s)
filePath = fullfile(s(kk).folder,s(kk).name);
x = csvread(filePath);
c{kk} = x(:);
end
% Find the minumul length
len = cellfun(@numel,c);
minLen = min(len);
% Delete minLen+1:end for each array in cell
c = cellfun(@(x) x(1:minLen),c,'UniformOutput',false);
% Concatenate them
All = cell2mat(c);
  댓글 수: 8
Akira Agata
Akira Agata 2020년 3월 16일
Oops!
Sorry, please change "c{kk} = x(:)" to "c{kk} = x".
Kong
Kong 2020년 3월 16일
Thank you so much!
I got it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by