Pschtoolbox matlab can't control the stimulus flow - matlab

I am working on a visual experiment using psychtoolbox (matlab). I was able to create the most basic experiment but I struggle with adjusting the stimulus presentation timing/order/length, etc.
I am trying to present a fixation cross continuously for 10 minutes and add text (same question) below the cross 12 times in 10 minutes in a randomized manner. Also, I want to get key responses (left or right) as answers to the question. I have to repeat this 4 times in a loop where you can take breaks of 5 minutes.
Below is the code I managed to create so far.
Could you please help?
% Clear the workspace and the screen
sca;
close all;
clear;
% Here we call some default settings for setting up Psychtoolbox
PsychDefaultSetup(2);
% Get the screen numbers
screens = Screen('Screens');
% Draw to the external screen if avaliable
screenNumber = max(screens);
% Define black and white
white = WhiteIndex(screenNumber);
black = BlackIndex(screenNumber);
grey = white / 2;
% Open an on screen window
[window, windowRect] = PsychImaging('OpenWindow', screenNumber, grey);
% Get the size of the on screen window
[screenXpixels, screenYpixels] = Screen('WindowSize', window);
% Query the frame duration
ifi = Screen('GetFlipInterval', window);
% Set up alpha-blending for smooth (anti-aliased) lines
Screen('BlendFunction', window, 'GL_SRC_ALPHA', 'GL_ONE_MINUS_SRC_ALPHA');
%----------------------------------------------------------------------
% Timing Information
%----------------------------------------------------------------------
% Interstimulus interval time in seconds and frames
isiTimeSecs = 5;
isiTimeFrames = round(isiTimeSecs / ifi);
% Numer of frames to wait before re-drawing
waitframes = 1;
%----------------------------------------------------------------------
% Keyboard information
%----------------------------------------------------------------------
% Define the keyboard keys that are listened for. We will be using the left
% and right arrow keys as response keys for the task and the escape key as
% a exit/reset key
escapeKey = KbName('ESCAPE');
leftKey = KbName('LeftArrow');
rightKey = KbName('RightArrow');
% Setup the text type for the window
Screen('TextFont', window, 'Times');
Screen('TextSize', window, 36);
% Get the centre coordinate of the window
[xCenter, yCenter] = RectCenter(windowRect);
% Here we set the size of the arms of our fixation cross
fixCrossDimPix = 40;
% Now we set the coordinates (these are all relative to zero we will let
% the drawing routine center the cross in the center of our monitor for us)
xCoords = [-fixCrossDimPix fixCrossDimPix 0 0];
yCoords = [0 0 -fixCrossDimPix fixCrossDimPix];
allCoords = [xCoords; yCoords];
% Set the line width for our fixation cross
lineWidthPix = 10;
% Draw the fixation cross in white, set it to the center of our screen and
% set good quality antialiasing
Screen('DrawLines', window, allCoords,...
lineWidthPix, white, [xCenter yCenter], 2);
% Draw text in the bottom of the screen in Times in white
Screen('TextSize', window, 40);
Screen('TextFont', window, 'Times');
DrawFormattedText(window, 'Sham (left) or Real TMS (right)?', 'center',...
screenYpixels * 0.75, white);
% Flip to the screen
Screen('Flip', window);
% Wait for a key press
KbStrokeWait;
% Clear the screen
sca;
enter code here

Related

PsychToolbox keeps crashing a few trials into experiment. Error on line 117 with using screen

This is an experiment with 32 trials. A circle and a smiley face appear on the screen. If the participants clicks the smiley face, a video plays. If they click the circle, it skips to the next trial. I am getting an error on line 117
[moviePtr movieDur]= Screen('OpenMovie', window, fullMovieName);
for screen about 8 trials in every time, even when I purposefully select the circle and no video plays.
%ITI setup
ITIlist=[1 1 3 5];
ITItmp=[repmat(ITIlist,[1,nTR/numel(ITIlist)])];
ITI=ITItmp(randperm(numel(ITItmp)));
% % %get images
stimImg(1,:,:,:)=imread(sprintf('Stim/circle.png'));
stimImgTexture(1)=Screen('MakeTexture',window,squeeze(stimImg(1,:,:,:)),[],[],0);
stimImg(2,:,:,:)=imread(sprintf('Stim/smiley.png'));
stimImgTexture(2)=Screen('MakeTexture',window,squeeze(stimImg(2,:,:,:)),[],[],0);
%get movies
MovieIndex=randperm(numel(MovieList));
stimMovie=MovieList(MovieIndex(1)).name;
% stimPath=stimulusList(tr).folder;
% stimPath=sprintf('%s\',stimulusList(1).folder);
MoviePath='G:\My Drive\ABCLab\Alexis\ECITT\VidList\';
fullMovieName=sprintf('%s%s',MoviePath,stimMovie);
Screen('FillRect', window, grey, wholeScreenRect);
Screen('Flip',window);
% WaitSecs(pretrialduration);
MovieList=dir('VidList/*mp4');
%randomize movies
% MovieIndex=randperm(numel(MovieList));
trialCounter=0;
ntestcards=2;
goodSeq=0;
if condition==1
domLoc=1;
stimorder=[repmat([1 2],[8 1]); repmat([2 1],[24 1])];
elseif condition==2
domLoc=2;
stimorder=[repmat([1 2],[24 1]); repmat([2 1],[8 1])];
end
while goodSeq==0
randorder=randperm(size(stimorder,1));
stimorderTmp=stimorder(randorder,:);
seqstoreDom=0;
seqstoreNonDom=0;
seqstoretmp=0;
for ix=2:numel(randorder)
if stimorderTmp(ix-1,1)==domLoc
if stimorderTmp(ix-1,1)==stimorderTmp(ix,1)
seqstoretmp=seqstoretmp+1;
else
seqstoreDom=[seqstoreDom seqstoretmp];
seqstoretmp=0;
end
else
if stimorderTmp(ix-1,1)==stimorderTmp(ix,1)
seqstoretmp=seqstoretmp+1;
else
seqstoreNonDom=[seqstoreNonDom seqstoretmp];
seqstoretmp=0;
end
end
end
if max(seqstoreDom)<6 & max(seqstoreNonDom)<4
goodSeq=1;
end
end
stimorder=stimorderTmp;
for tr=1: nTR
trialCounter=trialCounter+1;
fixPoint=Screen('DrawDots',window, [xCenter , yCenter],20,black,[],2);
Screen('Flip',window);
%card angles
stimXY=[(xCenter) (yCenter+400);(xCenter) (yCenter-400)]; %%can adjust if you don't like the location
stimCoords=[(xCenter-100) (yCenter+400-100) (xCenter+100) (yCenter+400+100);(xCenter-100) (yCenter-400-100) (xCenter+100) (yCenter-400+100) ];
initWait=1;
while initWait
[keyIsDown,secs, keyCode]=KbCheck;
if keyCode(escKey)
sca
return
elseif keyCode(initKey)
initWait=0;
end
preloadsecs=1;
pixelFormat=[];
maxThreads=[];
[moviePtr movieDur]= Screen('OpenMovie', window, fullMovieName);
Screen('PlayMovie', moviePtr, 1, 1, 1);
tStart=GetSecs;
ListenChar(0); %allows keypresses again
end
for arrayInd=1:ntestcards
Screen('DrawTexture',window,stimImgTexture(1,arrayInd),[],stimCoords(orientation(arrayInd),:));
end
Screen('Flip',window);
tStart = GetSecs;
% stim marks
cw_ser = serial('com4'); %
set(cw_ser,'BaudRate',9600,'DataBits',8,'Parity','none','StopBits',1,'FlowControl','none','Terminator',13);
fopen(cw_ser);
fprintf(cw_ser,'1'); %send a "1" to the interface to active BNC connector#1 to TTL High
pause(0.15); %Must wait ~120 - 150 ms to allow CW6 to capture
fprintf(cw_ser,'0'); %send a "0" to the interface to all BNC connectors to TTL Low
fclose(cw_ser);
%get clicks
respWait=1;
xClick=[];
yClick=[];
buttons=[];
clickDist=[];
SetMouse(1,1);
while respWait
% [clicks, xClick, yClick, whichbutton] = GetClicks;
% [xClick,yClick,buttons] = GetMouseTransient(window,1);
% clickXY=[xClick yClick];
[xClick,yClick,buttons] = GetMouse(window,1);
clickXY=[xClick yClick];
clickDist=sqrt( (clickXY(1)-stimXY(:,1)).^2 + (clickXY(2)-stimXY(:,2)).^2);
% if any(buttons)
if min(clickDist)<100 %Might need to adjust
respLoc=find(clickDist==min(clickDist));
rtTime=GetSecs;
respWait=0;
end
% end
end
acc = respLoc == orientation(2);
if acc==1
Screen('Flip',window);
while GetSecs<tStart+movieDur
texture = Screen('GetMovieImage', window, moviePtr);
if texture ==0
WaitSecs('YieldSecs',.005);
continue;
end
Screen('DrawTexture', window, texture);
Screen('Flip', window);
Screen('Close',texture);
end
Screen('CloseMovie',moviePtr);
Screen('FillRect', window, grey, wholeScreenRect);
Screen('Flip',window);
tEnd = GetSecs;
rt = rtTime - tStart;
Screen('Clear')
Screen('FillRect', window, grey, wholeScreenRect);
Screen('Flip',window);
WaitSecs(ITI(tr));
end
end
I have tried deleting several of the videos, it doesn't seem to be an issue with any of them. It also still crashes even when I only select the "incorrect" response (the circle) which would result in no videos being played.

How to stop particles crossing the solid cylinder boundary?

I am doing a random walk particle tracking simulation. In my problem, I have to implement a reflected boundary on the cylinder. In this code, the check implies that if particles enter into the cylinder, their previous position should not change. I mean, if a particle crosses the solid boundary, such a move is rejected, and the tracer stays at its previous position during the current iteration. For clarification, I have attached an image where you can see particle sitting in the circle.
However, particles still entering into the cylinder. Below is my code.
%% loop starts
for i = 1:T % T is the total computation time of simulation
t = i*dt; % dt is the time step
%% Particle tracking starts
x_ out = x_previous + u.dt + sqrt(2Ddt); % x_out--> current position
% x_previous--> previous position
% u -> x-velocity component
y_ out = y_previous + v.dt + sqrt(2Ddt); % y_out--> current position
% y_previous--> previous position
% v -> y-velocity component
%% Check whether particle is inside the cylinder obstacle
% x_c and y_c is the center location for cylinder (obstacle) in the flow
Incircle = sqrt((x_out - x_c).^2 + (y_out - y_c).^2);
Particle_enter = find (Incircle < D/2); % Particle entered in obstacle
% having diameter (D)
%% if particle cross cylinder boundary, do not update its position
if ismember(Particle_enter,1)
kk1 = find(ismember(isIncircle, 1) == 1);
x_out(kk1) = x_previous(kk1); % Do not update location
y_out(kk1) = y_previous(kk1);
end
x_previous = x_out;
y_previous = y_out;
end
Any modification/correction will be helpful
Thanks
Due to rounding error, when comparing float or double, use
a-b > tol % tol = some error tolerance, say, 1e-10
instead of
a > b
Also, sqrt can introduce some numerical error, comparing the squared distance is more accurate.
Try to change these lines in your code into
Incircle = (x_out - x_c).^2 + (y_out - y_c).^2;
Particle_enter = find (abs(Incircle - D^2/4) < tol);
If you randomly generate the initial positions of the particles, make sure they are not inside the obstacle in the first place.
Finally, if a particle hits a reflected boundary, shouldn't it be reflected, instead of returning to where it was?

Dot moves from corner to corner (around monitor) in matlab

I am trying to do create a ball or dot or whatever that goes from left bottom corner to right bottom corner then top right corner then left top corner then on the start so left bottom corner. Basically around the screen. And in total fullscreen that important. For fullscreen graph i am using WindowAPI.
So here is my code.
try
% Create a figure to operate on: --------------------------------------------
% The OpenGL renderer is confused by the alpha blending, so Painters is used:
FigH = figure('Color', ones(1, 3), 'Renderer', 'Painters');
axes('Visible', 'off', 'Units', 'normalized', 'Position', [0, 0, 1, 1]);
% Set topmost status:
WindowAPI(FigH, 'topmost'); % Command is not case-sensitive
drawnow;
WindowAPI(FigH, 'TopMost', 0);
drawnow;
WindowAPI(FigH, 'front');
drawnow;
% Nicer to have the figure on topmost for the rest of the demo:
WindowAPI(FigH, 'topmost');
% Special maximizing such that the inner figure fill the screen:
WindowAPI(FigH, 'Position', 'full'); % Complete monitor
% START MOVING BALL
X = 2;
Y = 0;
for i=1:1490
X = X + 0.1;
Y = 2
plot(X,Y,'or','MarkerSize',20,'MarkerFaceColor','r')
axis([0 151 0 85])
pause(0)
end
% END MOVING BALL
end
For simplicity that dot goes only from left to right bottom corner.
But there are two problems.
that dot lag sometimes which is a problem.
There are visible black lines (from the graph).
And I don't know how to fix these two problems. So if u know how to fix them or any better way how to animate ball in Matlab please post it here. Thanks for your time.
To reduce the amount of 'Lag' you can do a few of the following:
Move the plot line outside of the loop and assign it to a handle, additionally move the axis commandos out with it
pH = plot(X,Y,'or','MarkerSize',20,'MarkerFaceColor','r');
axis([0 151 0 85])
axis off
Now you can update the X Y data directly in the loop.
set(pH,'XData',X,'YData',Y)
Replace the pause with (replace 0 with the length in seconds that you want to delay the frame by):
tic;while toc<0;end
This is faster, more precise, and does not cause an interrupt to MatLab.
Add the drawnow command in the loop to cause the figures to update.

Matlab click zoom disables for the second time of the loop

Consider the following example
ax(1) = subplot(2,1,1)
plot(1:100,rand(1,100))
ax(2) = subplot(2,1,2)
plot(1:100,rand(1,100))
hzoom(1) = zoom(ax(1));
hzoom(1).Motion = 'horizontal';
hzoom(2) = zoom(ax(2));
hzoom(2).Motion = 'horizontal';
zoom on
linkaxes(ax, 'x');
waitforbuttonpress;
while 1
[x, ~] = ginput(2);
zoom on
waitforbuttonpress;
click_break = waitforbuttonpress;
if(click_break)
break;
end
end
In the above plots for the first time of the loop the mouse cursor is magnifying glass and i can zoom into a data by simply selecting it
and here we can see the data is zoomed in
but when i have clicked twice (for the ginput to get datapoints) and the loop runs in the next iteration the cursor doesnt magnify/zoom by selecting the specific data , I know we can also zoom in by scrolling but my scroll has developed some problem the magnification converges to centre data points so the only posibility is data selection through mouse click, am I missing any function in my loop?

Is there a way to make a value equal to a set of updating values?

I know it's not the best wording but I really need some help here..
I have a PingPong game that I want to make automated. I want to try make the paddle's centre coordinate ((Py1 + Py2) / 2) {Top Y + Bottom Y / 2} equal to the ball's centre coordinate ((By1 + By2) / 2){Same as paddle}.
I want to know if there's a way to constantly change the paddle coordinates to adjust to the ball's coordinates. The whole program uses 'Thrusters' as direction and speed.
Thruster(2) = Fast
Thruster(1) = Slows down, and eventually changes direction
Thruster(0) = Keeps momentum
Thruster(-1) = Changes direction.
http://www.mathworks.com/matlabcentral/fileexchange/45619-pingpong-game
Pretty sure this is the original file..
I'm new to the whole coding thing, in case that wasn't obvious..
Thanks
The code:
function GAME_PINGPONG
% PingPong game
% Every time the player gets 2 correct deflections the speed of play
% increases.
% [x,y] = Get_Ball_Coordinates()
% This function returns the x and y coordinates of the ball
% [y,V] = Get_Paddle_Info()
% This will return the y coordinates of the paddle (y) and its speed (V)
% Thruster()
% This controls the speed of the paddle.
% Thruster(2) increases the speed of the paddle in the up
% direction/decreases in down
% Thruster(1) decreases the speed of the paddle in the up direction/
% increases in down
% Thruster(0) maintains the speed of the paddle
% Thruster(-1) reverses the direction of the paddle (maintains speed)
%% Set up simulation
global Game_Over Mode h
close all;clc;
SET_UP_SIM; % Set up the simulation and associated timers etc.
Game_Over =0; % When this changes to 1 the game is over!!!
%% Mode of operation
% Auto mode: write a script to control the bat
% Manual mode: use uparrow and downarrow to control the bat
Mode = 0; % Mode= 1 is AUTO, Mode=0 is MANUAL
%% Auto mode: Control algorithm
while(Mode==1) % While auto mode is selected the following actions will be carried out
[Bx,By] = Get_Ball_Coordinates(); % Use function Get_Ball_Coordinates() to return x and y values of the ball
[Py,PV] = Get_Paddle_Info(); % Use function Get_Paddle_Info() to return the y coordinates of the paddle and it's speed.
if Game_Over==1 % Suggest a logic test to break out of continuous auto mode when the game is over!
break
end
end