For loop: saving variables for each iteration

7 次查看(过去 30 天)
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