Generate new file w/ each iteration of for loop. Problem of same output in each new file?

1 Ansicht (letzte 30 Tage)
Hi,
I'm trying to design a for loop that takes 100 random rows from a sample data set, and saves that into a new output file, one hundred times. I can get all of the output files, but each file contains the same row values. I'm not sure where the problem is?
Here's my code:
thissample = xlsread('~/Documents/mdd_with_anx.xls');
sampSets = 1;
randSampNum = 1;
for sampSets = 1:100;
N = 100;
c=randperm(length(thissample),N);
randSampSet=thissample(c,:);
for randSampNum = 1:100
filename = ['randSamp' num2str(randSamp) '.csv'];
csvwrite(filename,randSamp);
randSampNum = randSampNum + 1;
end;
sampSets = sampSets + 1;
end;
  1 Kommentar
Ced
Ced am 20 Jan. 2015
Bearbeitet: Ced am 20 Jan. 2015
Where do you assign a value to randSamp? Also, you probably meant to write
filename = ['randSamp' num2str(randSampNum) '.csv'];
On a sidenote, the initialization of sampSets = 1 and randSampNum = 1 is not necessary. What you are essentially doing is first initialize it as a scalar (1), and then re-define it as a vector in the for loop (e.g. sampSets = 1:100)
Also, sampSets = sampSets + 1 is not necessary, same for randSampNum = randSampNum + 1.
A simple for loop looks like this:
for i = 1:10
sprintf('This is iteration: %i \n',i)
end
This would return
This is iterations: 1
This is iterations: 2
This is iterations: 3
This is iterations: 4
This is iterations: 5
This is iterations: 6
This is iterations: 7
This is iterations: 8
This is iterations: 9
This is iterations: 10

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Voss
Voss am 13 Jan. 2022
thissample = xlsread('~/Documents/mdd_with_anx.xls');
thissample_size = size(thissample,1);
N = 100;
if thissample_size < N
error('Unable to pick %d random rows: the input matrix only has %d rows',N,thissample_size);
end
for sampSets = 1:100
csvwrite(['randSamp' num2str(sampSets) '.csv'],thissample(randperm(thissample_size,N),:));
end

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by