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

1 次查看(过去 30 天)
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 个评论
Ced
Ced 2015-1-20
编辑:Ced 2015-1-20
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

请先登录,再进行评论。

回答(1 个)

Voss
Voss 2022-1-13
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by