필터 지우기
필터 지우기

How to split a number into 5 parts equalling the sum of the number

조회 수: 12 (최근 30일)
MKM
MKM 2022년 3월 10일
답변: Walter Roberson 2022년 3월 11일
So i am trying to create a code that reads a large CSV that:
  • counts the rows
  • divides the rows by 5
  • create an array that stores these parts [1 1part 2part 3part 4part 5part]
  • create a new csv's.parts(1-5)
So read a csv and split it into 5 parts.
The idea i had was splitNum = rowcount/5 and then splitArray = [1:rowcount:totalrows] and then loop the table with this array until done
but ofcourse this doesnt equal the total number of rows properly.
What would be a better solution for this?
Thanks

답변 (2개)

Jon
Jon 2022년 3월 10일
Not sure exactly what you are expecting, but obviously if your total number of rows is not a multiple of 5 then you cannot split your original file into 5 files with equal number of rows.
If you want you could have all but the last file have the same number of rows using
n = floor(totalrows/5)
split = 1:n:totalrows
So for example if totalrows = 23, then you would have 5 files, each with 4 rows and then the last one would have only 3.
  댓글 수: 1
MKM
MKM 2022년 3월 11일
Yep exactly, i managed to solve the problem in the end with the similar way you thought out here. I count the total rows in the main CSV (say 220000) divided that by a total number of rows i want each individual CSV to have(say 50000). This give me the count of how many files i would have. (floor(220000/5)) =4
after i have this number i itterate 3 files with 50000 rows (150000). once it reaches the last count (file 4) i use end to get the next 50000 + anything after (20000) this gives me 3 files with 50000 rows and 1 files with a little bit extra.

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


Walter Roberson
Walter Roberson 2022년 3월 11일
CSV = readmatrix(filename) ;
R = size(CSV, 1);
N = floor(R/5);
parts = mat2cell(CSV, [N, N, N, N, R-4*N],size(CSV, 2));
Now write out parts{1} to 5
The last part might be up to 4 samples larger.

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by