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
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
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!