How do I automate breakdown of an array into smaller arrays?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dylan Barber
am 18 Apr. 2021
Bearbeitet: Dylan Barber
am 21 Apr. 2021
Hi everyone,
I have a number of nx3 arrays where n changes from data set to data set. I would like to take each data set (for example, randomly generated array 'r1' below, with 23 rows) and turn it into n-3 arrays, each with 4 rows (i.e. r1(1:4,:), r2(2:5,:),..., r3(20:23,:), and write each as a separate text file. I am stuck on the step of creating the n-3 (in this case 20, but again, n varies so I can't just assign a specific number of new arrays across all of my data sets) new arrays. When I run the following for loop:
>> for k=1:(size(r1,1)-3)
v=[r1(k:k+3,:)]
end
it outputs each of the arrays I want, but each time with the name 'v' so that when I export with writematrix(v), I can only export the last array output by the for loop (and the other 22 are lost). I would really rather avoid copy/pasting each 4x3 array into separate text files because I have a lot of data and it would take a long time. I also acknowledge that it's preferable to use efficient indexing over creation of dynamic variables as explained here https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval?s_tid=srchtitle. I'll keep working my way through the documentation but at this point I would welcome any guidance/syntax/functions/operations. Thanks! Also, example data set below:
>> rng('default')
>> r1=rand(23,3)
r1 =
0.8147 0.9340 0.4456
0.9058 0.6787 0.6463
0.1270 0.7577 0.7094
0.9134 0.7431 0.7547
0.6324 0.3922 0.2760
0.0975 0.6555 0.6797
0.2785 0.1712 0.6551
0.5469 0.7060 0.1626
0.9575 0.0318 0.1190
0.9649 0.2769 0.4984
0.1576 0.0462 0.9597
0.9706 0.0971 0.3404
0.9572 0.8235 0.5853
0.4854 0.6948 0.2238
0.8003 0.3171 0.7513
0.1419 0.9502 0.2551
0.4218 0.0344 0.5060
0.9157 0.4387 0.6991
0.7922 0.3816 0.8909
0.9595 0.7655 0.9593
0.6557 0.7952 0.5472
0.0357 0.1869 0.1386
0.8491 0.4898 0.1493
4 Kommentare
Stephen23
am 18 Apr. 2021
for k = ..
v = ..
f = sprintf('data_%d.txt',k);
writematrix(v,f)
end
Akzeptierte Antwort
David Fletcher
am 18 Apr. 2021
Bearbeitet: David Fletcher
am 18 Apr. 2021
for k=1:(size(r1,1)-3)
v(:,:,k)=[r1(k:k+3,:)]
end
All 4x3 matrices will be held in v indexable by the third dimension of v
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!