For loop: saving variables for each iteration

7 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Fangjun Jiang
Fangjun Jiang il 22 Gen 2018
Modificato: Fangjun Jiang il 23 Gen 2018
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 Commenti
Giulia Orioli
Giulia Orioli il 23 Gen 2018
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 il 23 Gen 2018
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

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by