Colored Gabors in Psychtoolbox

The following code will allow you to create colored gabors in psychtoolbox + MATLAB that can be any color and can have peak and trough values of any color and can also fade into any color. The DrawGabor() function sets up the environment and screen while the GenerateGabor() function generates the gabor.

function DrawGabor()
    %screen init for PC and MAC
    KbName('UnifyKeyNames');
    Screen('Preference', 'SkipSyncTests', 1);
    Screen('CloseAll');   
    MyScreens = Screen('Screens');
    screen.id = max(MyScreens);
    screen.win = Screen('OpenWindow', screen.id, 127.5);
    screen.resolution = Screen('Resolution',screen.id);
    screen.width = screen.resolution.width;
    screen.height = screen.resolution.height;
    screen.width
    HideCursor();
    gabortex = generate_gabor(0,40,20,.1,0,[125,125,125],[0,0,0],[255,0,0]);
    drawtex=Screen('MakeTexture', screen.win, gabortex);
    Screen('DrawTexture', screen.win, drawtex);
    Screen('Flip', screen.win);
return;
function [gabortex] = generate_gabor(orient,size,std,freq,phase,color0,color1,color2)
gabortex = [];
orient = deg2rad(orient);
for rx=1:(std*size)
    for ry=1:(std*size)
        dx = rx - .5 * (std*size);
        dy = ry - .5 * (std*size);
        t = atan2(dy,dx) + orient;
        r = (dx * dx + dy*dy)^.5;
        x = r * cos(t);
        y = r * sin(t);
        amp = 0.5 + 0.5 * cos (2 * pi * (x * freq + phase));
        f = exp(-0.5 * (x/std)^2 - .5 * (y/std)^2);
        r = color1(1) * amp + color2(1) * (1-amp);
        g = color1(2) * amp + color2(2) * (1-amp);
        b = color1(3) * amp + color2(3) * (1-amp);
        gabortex(rx,ry,1) = r * f + color0(1)*(1-f);
        gabortex(rx,ry,2) = g * f + color0(2)*(1-f);
        gabortex(rx,ry,3) = b * f + color0(3)*(1-f);
    end
end
return;