For loop: saving variables for each iteration

조회 수: 7 (최근 30일)
Giulia Orioli
Giulia Orioli 2018년 1월 22일
댓글: Fangjun Jiang 2018년 1월 23일
Hi,
I am just starting using MatLab, so please accept my apologies if this question sounds very stupid or easy. I have tried reading many questions that seemed related but did not find the solution to my problem (or at least I didn't recognise it as such).
I am creating an experiment (using Psychtoolbox) that uses a for loop. Within this loop there is a random permutation of an array. What I would like to do is obtaining, at the end of the loop, a matrix/xls file/csv file showing in consecutive lines the value of the permutation for each iteration of the loop.
My script looks like this:
for j = 1:4
AvailableTrials = [1 2 3 4];
ATsize = numel(AvailableTrials);
MyTrial = AvailableTrials(randperm(ATsize, 1))
if MyTrial == 1
runscriptone; % these are other scripts already present in the same directory
elseif MyTrial == 2
runscripttwo;
else
runscriptthree;
end
end
I would like my output to look something like this:
j . MyTrial
1 . 2
2 . 4
3 . 1
4 . 2
5 . 3
6 . 1
etc
I hope this makes sense and that somebody will be able to help me. Thank you!

채택된 답변

Fangjun Jiang
Fangjun Jiang 2018년 1월 22일
편집: Fangjun Jiang 2018년 1월 23일
Add a few lines to create your desired output in a text file.
fid=fopen('output.txt','w+t');
fprintf(fid,'j . MyTrial\n');
for j = 1:4
AvailableTrials = [1 2 3 4];
ATsize = numel(AvailableTrials);
MyTrial = AvailableTrials(randperm(ATsize, 1))
if MyTrial == 1
runscriptone; % these are other scripts already present in the same directory
elseif MyTrial == 2
runscripttwo;
else
runscriptthree;
end
fprintf(fid,'%d . %d\n',j,MyTrial);
end
fclose(fid);
  댓글 수: 2
Giulia Orioli
Giulia Orioli 2018년 1월 23일
Hi Fangjun, thank you for your answer. This works, but records only the information for the last trial, not for all of them.
Fangjun Jiang
Fangjun Jiang 2018년 1월 23일
There is one typo. In the last fprintf() line, the loop variable should be j (instead of i previously). However, if you've figured this out already, I thought the output was right, like below
j . MyTrial
1 . 4
2 . 1
3 . 3
4 . 2

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Timing and presenting 2D and 3D stimuli에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by