For loop: saving variables for each iteration

7 visualizaciones (últimos 30 días)
Giulia Orioli
Giulia Orioli el 22 de En. de 2018
Comentada: Fangjun Jiang el 23 de En. de 2018
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!

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 22 de En. de 2018
Editada: Fangjun Jiang el 23 de En. de 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 comentarios
Giulia Orioli
Giulia Orioli el 23 de En. de 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 el 23 de En. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Timing and presenting 2D and 3D stimuli en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by