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

11 Ansichten (letzte 30 Tage)
MKM
MKM am 10 Mär. 2022
Beantwortet: Walter Roberson am 11 Mär. 2022
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

Antworten (2)

Jon
Jon am 10 Mär. 2022
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 Kommentar
MKM
MKM am 11 Mär. 2022
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.

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 11 Mär. 2022
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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by