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

3 views (last 30 days)
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 Comment
Ced
Ced on 20 Jan 2015
Edited: Ced on 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

Sign in to comment.

Answers (1)

Voss
Voss on 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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!