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

15 ビュー (過去 30 日間)
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'
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?

回答 (2 件)

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 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索




Community Treasure Hunt

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

Start Hunting!

Translated by