MATLAB, How to visualize my directional beam Data - matlab

I've made an experiment with directional beams and I would like to visualise it. The set-up was like this:
I've measured my values at 22, 15, 10, 5 and 0 degrees in a distance of 100, 75, 50 and 25 cm.
Now I would like to bring this Data into a 3D waterfall() diagram where the source is the highest peak and you can see that the voltage decreases in all directions.
So my first thought was to fit all distances individually and these functions I would like to put them into the waterfall(). But this doesn't work very well, because the begin and end different layers of values (have a look at the example code) after I calculate them to the x, y system was different.
So, how can I bring my data into a waterfall diagram?
clearvars
x=-1:0.1:1;
%________________________________________________________measured Values (layers)
A=[208; 256; 480; 704; 776; 752; 672; 480; 264]; % 0.25m
B=[104; 156; 304; 388; 432; 440; 340; 280; 140]; % 0.50m
C=[ 54; 104; 250; 264; 320; 270; 252; 144; 70]; % 0.75m
D=[ 32; 64; 142; 198; 228; 208; 130; 86; 46;]; % 1.00m
% plot(A)
% figure(2)
% plot(B)
% figure(3)
% plot(C)
% figure(4)
% plot(D)
%________________________________________________________to x,y System
dist1=[tand(-22)*0.25; tand(-15)*0.25; tand(-10)*0.25; tand(-5)*0.25; tand(0)*0.25; tand(5)*0.25; tand(10)*0.25; tand(15)*0.25; tand(22)*0.25;];
dist2=[tand(-22)*0.50; tand(-15)*0.50; tand(-10)*0.50; tand(-5)*0.50; tand(0)*0.50; tand(5)*0.50; tand(10)*0.50; tand(15)*0.50; tand(22)*0.50;];
dist3=[tand(-22)*0.75; tand(-15)*0.75; tand(-10)*0.75; tand(-5)*0.75; tand(0)*0.75; tand(5)*0.75; tand(10)*0.75; tand(15)*0.75; tand(22)*0.75;];
dist4=[tand(-22); tand(-15); tand(-10); tand(-5); tand(0); tand(5); tand(10); tand(15); tand(22)];
plot(dist1,A)
figure(2)
plot(dist2,B)
figure(3)
plot(dist3,C)
figure(4)
plot(dist4,D)
% func1= fit(dist1,A,'poly2')
%
% plot(dist1, func1(dist1))
Furthermore:
As a result I would like to create something like this:
http://de.mathworks.com/help/matlab/ref/waterfall.html
or maybe a surface:
http://de.mathworks.com/help/matlab/ref/surf.html
But I don't know how I can convert my current data into a format, which fits the requirements of the waterfall() or surf() function

It's all about organizing your data. As Daniel said, waterfall (or even surf for that matter) require a mesh as input (your data need to be matrices).
So let's build a proper mesh with your data:
%% // measured Values (layers)
A = [208; 256; 480; 704; 776; 752; 672; 480; 264] ; %// 0.25m
B = [104; 156; 304; 388; 432; 440; 340; 280; 140] ; %// 0.50m
C = [ 54; 104; 250; 264; 320; 270; 252; 144; 70] ; %// 0.75m
D = [ 32; 64; 142; 198; 228; 208; 130; 86; 46] ; %// 1.00m
%% // Building the mesh
%// primary parameters
x = (0.25:0.25:1).' ; %'// ignore that comment
angles = [-22 -15 -10 -5 0 5 10 15 22] ;
%// mesh matrices
X = x * ones(1,numel(angles)) ; %// distance to source
Y = x * tand(angles) ; %// lateral spread due to angle
V = [A B C D].' ; %'// measurements (voltages)
At this point, you have 3 matrices X,Y and V which are perfect input for most 3D graphing functions like surf or waterfall. So it becomes quite straightforward:
%% // Waterfall visualisation
hf = figure ;
hw = waterfall(X,Y,V) ;
If you want to add some refinements :
%% // refinements
shading interp
xlabel('Distance to source')
ylabel('Lateral spread')
zlabel('Voltage')
hold on
plot3(0,0,0,'or','MarkerSize',10,'LineWidth',4) %// show the source position
and/or even more information on the figure:
%% // displays the base rays
xrays = [0;x] ;
yrays = [zeros(1,numel(angles)) ; Y] ;
set(0,'DefaultAxesColorOrder',[0 0 0] , 'DefaultAxesLineStyleOrder','--|:' )
plot(xrays,yrays,'Marker','.')
At this stage, it yields the following figure, but you can keep it simple or adjust many other properties of all the graphic object to personalize your display:
You can also play with the surf function instead of waterfall, and use the same matrices as input.
Another way to better link the voltage recorded for every sensor position would be to use a stem plot. Unfortunately the stem function does not take 3D arrays as input, however, the ZData property still exist so we can instantiate the stem plot first then loop through them to set their ZData:
%% // STEM waterfall variant
hsf = figure ; hold on
hs = stem(X.',Y.',':ob') ;
for k=1:4
set(hs(k),'ZData',V(k,:))
end
With all the refinements above, it yields:
This variant doesn't color code the voltage but it shows exactly the position where it was recorded.

Easiest way is to mesh your data first (i.e. put them in X, Y and Z matrices):
%Z:
dist1234=[dist1 dist2 dist3 dist4];
%Y:
ABCD=[A B C D];
%X:
[n1,n2]=size(ABCD);
X=repmat(1:n2,n1,1); % or whatever your x-axis is, here it is 1, 2, 3...
% Take your pick:
figure(1)
surf(X,dist1234,ABCD);title('surf')
figure(2)
waterfall(X',dist1234',ABCD');title('waterfall')
figure(3)
mesh(X,dist1234,ABCD);title('mesh')

Related

Creating a circle in a square grid

I try to solve the following 2D elliptic PDE electrostatic problem by fixing the Parallel plate Capacitors code. But I have problem to plot the circle region. How can I plot a circle region rather than the square?
% I use following two lines to label the 50V and 100V squares
% (but it should be two circles)
V(pp1-r_circle_small:pp1+r_circle_small,pp1-r_circle_small:pp1+r_circle_small) = 50;
V(pp2-r_circle_big:pp2+r_circle_big,pp2-r_circle_big:pp2+r_circle_big) = 100;
% Contour Display for electric potential
figure(1)
contour_range_V = -101:0.5:101;
contour(x,y,V,contour_range_V,'linewidth',0.5);
axis([min(x) max(x) min(y) max(y)]);
colorbar('location','eastoutside','fontsize',10);
xlabel('x-axis in meters','fontsize',10);
ylabel('y-axis in meters','fontsize',10);
title('Electric Potential distribution, V(x,y) in volts','fontsize',14);
h1=gca;
set(h1,'fontsize',10);
fh1 = figure(1);
set(fh1, 'color', 'white')
% Contour Display for electric field
figure(2)
contour_range_E = -20:0.05:20;
contour(x,y,E,contour_range_E,'linewidth',0.5);
axis([min(x) max(x) min(y) max(y)]);
colorbar('location','eastoutside','fontsize',10);
xlabel('x-axis in meters','fontsize',10);
ylabel('y-axis in meters','fontsize',10);
title('Electric field distribution, E (x,y) in V/m','fontsize',14);
h2=gca;
set(h2,'fontsize',10);
fh2 = figure(2);
set(fh2, 'color', 'white')
You're creating a square due to the way you're indexing (see this post on indexing). You've specified the rows to run from pp1-r_circle_small to pp1+r_circle_small and similar for the columns. Given that Swiss cheese is not an option, you're creating a complete square.
From geometry we know that all points within distance sqrt((X-X0)^2 - (Y-Y0)^2) < R from the centre of the circle at (X0,Y0) with radius R are within the circle, and the rest outside. This means that you can simply build a mask:
% Set up your grid
Xsize = 30; % Your case: 1
Ysize = 30; % Your case: 1
step = 1; % Amount of gridpoints; use 0.001 or something
% Build indexing grid for circle search, adapt as necessary
X = 0:step:Xsize;
Y = 0:step:Ysize;
[XX,YY] = meshgrid(X, Y);
V = zeros(numel(X), numel(Y));
% Repeat the below for both circles
R = 10; % Radius of your circle; your case 0.1 and 0.15
X0 = 11; % X coordinate of the circle's origin; your case 0.3 and 0.7
Y0 = 15; % Y coordinate of the circle's origin; your case 0.3 and 0.7
% Logical check to see whether a point is inside or outside
mask = sqrt( (XX - X0).^2 + (YY - Y0).^2) < R;
V(mask) = 50; % Give your circle the desired value
imagesc(V) % Just to show you the result
axis equal % Use equal axis to have no image distortion
mask is a logical matrix containing 1 where points are within your circle and 0 where points are outside. You can then use this mask to logically index your potential grid V to set it to the desired value.
Note: This will, obviously, not create a perfect circle, given you cannot plot a perfect circle on a square grid. The finer the grid, the more circle-like your "circle" will be. This shows the result with step = 0.01
Note 2: You'll need to tweek your definition of X, Y, X0, Y0 and R to match your values.

Fancy Correlation Plots in MATLAB

I'm trying to find a way to generate these pretty correlation plots in MATLAB. These are generated in R using 'corrplot' function, but couldn't find any similar code in MATLAB. Any help would be appreciated.
As a quick description, this function will create a color scale of the correlation values, and create circles in each cell of the correlation matrix/plot with the associated color. The size of the circles is also an indicator of the magnitude of the correlation, with larger circles representing a stronger relationship (positive or negative). More details could be found here.
you can use plot-corrmat (or modify it, depending how articulate you are in matlab), to obtain similar visualizations of correlation matrices (top pic). Or use Correlation circles , that looks somewhat similar as well (bottom pic)...
https://github.com/elayden/plot-corrmat
I could write the below code to generate a similar graph, based on the code provided here
% Produce the input lower triangular matrix data
C = -1 + 2.*rand(12,12);
C = tril(C,-1);
C(logical(eye(size(C)))) = 1;
% Set [min,max] value of C to scale colors
clrLim = [-1,1];
% load('CorrColormap.mat') % Uncomment for custom CorrColormap
% Set the [min,max] of diameter where 1 consumes entire grid square
diamLim = [0.1, 1];
myLabel = {'ICA','Elev','Pr','Rmax','Rmin','Srad','Wspd','Tmin','Tmax','VPD','ET_o','AW'};
% Compute center of each circle
% This assumes the x and y values were not entered in imagesc()
x = 1 : 1 : size(C,2); % x edges
y = 1 : 1 : size(C,1); % y edges
[xAll, yAll] = meshgrid(x,y);
xAll(C==0)=nan; % eliminate cordinates for zero correlations
% Set color of each rectangle
% Set color scale
cmap = jet(256);
% cmap = CorrColormap; % Uncomment for CorrColormap
Cscaled = (C - clrLim(1))/range(clrLim); % always [0:1]
colIdx = discretize(Cscaled,linspace(0,1,size(cmap,1)));
% Set size of each circle
% Scale the size between [0 1]
Cscaled = (abs(C) - 0)/1;
diamSize = Cscaled * range(diamLim) + diamLim(1);
% Create figure
fh = figure();
ax = axes(fh);
hold(ax,'on')
colormap(ax,'jet');
% colormap(CorrColormap) %Uncomment for CorrColormap
tickvalues = 1:length(C);
x = zeros(size(tickvalues));
text(x, tickvalues, myLabel, 'HorizontalAlignment', 'right');
x(:) = length(C)+1;
text(tickvalues, x, myLabel, 'HorizontalAlignment', 'right','Rotation',90);
% Create circles
theta = linspace(0,2*pi,50); % the smaller, the less memory req'd.
h = arrayfun(#(i)fill(diamSize(i)/2 * cos(theta) + xAll(i), ...
diamSize(i)/2 * sin(theta) + yAll(i), cmap(colIdx(i),:),'LineStyle','none'),1:numel(xAll));
axis(ax,'equal')
axis(ax,'tight')
set(ax,'YDir','Reverse')
colorbar()
caxis(clrLim);
axis off
The exact graph is available here:
Fancy Correlation Plots in MATLAB

Does anybody know how should I use animatedline in order to draw me an orbit immediately?

This is the main code
%%%%%%%%%%%% Valori pentru Rcsc
%%%%Pozitiile si vitezele pe cele 3 axe
y0(1,1)= 743322.3616 ;
y0(2,1)= -6346021.219 ;
y0(3,1)= -3394131.349 ;
y0(4,1)= 5142.38067;
y0(5,1)= 4487.44895 ;
y0(6,1)= -7264.00872;
%%%% Timpul
tspan=[0 :864];
%%%% Masa(kg) si aria suprafetei satelitului (m^2)
m = 217 ; %320;
A = 1.2; %8;
%%%% Metoda Runge-Kutta de ordin 4
h=1;
y = zeros(6, tspan(end)/h);
y(:,1) = y0;
for i=1:(tspan(end)/h)
H=sqrt(y(1,i)^2+y(2,i)^2+y(3,i)^2);
k_1 = proiectia(tspan(i), y(:,i), H, m, A, y(4:6, i));
k1=double(k_1);
k_2 = proiectia(tspan(i)+0.5*h, y(:,i)+0.5*h*k_1, H, m, A, y(4:6, i));
k2=double(k_2);
k_3 = proiectia((tspan(i)+0.5*h), (y(:,i)+0.5*h*k_2), H, m, A, y(4:6, i));
k3=double(k_3);
k_4 = proiectia((tspan(i)+h),(y(:,i)+k_3*h), H, m, A, y(4:6, i));
k4=double(k_4);
y(:,i+1) = double(y(:,i) + (1/6)*(k1+2*k2+2*k3+k4)*h);
end
%%% Distanta satelitului
Rcsc = ((y(1,:).^2 + y(2,:).^2 + y(3,:).^2).^0.5);
n=50;
%plot(tspan,Rcsc)
%% Textured 3D Earth example
%
% Ryan Gray
% 8 Sep 2004
% Revised 9 March 2006, 31 Jan 2006, 16 Oct 2013
%% Options
space_color = 'k';
npanels = 180; % Number of globe panels around the equator deg/panel = 360/npanels
alpha = 1; % globe transparency level, 1 = opaque, through 0 = invisible
GMST0 = []; % Don't set up rotatable globe (ECEF)
%GMST0 = 4.89496121282306; % Set up a rotatable globe at J2000.0
% Earth texture image
% Anything imread() will handle, but needs to be a 2:1 unprojected globe
% image.
image_file = 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cd/Land_ocean_ice_2048.jpg/1024px-Land_ocean_ice_2048.jpg';
% Mean spherical earth
erad = 6371008.7714; % equatorial radius (meters)
prad = 6371008.7714; % polar radius (meters)
erot = 7.2921158553e-5; % earth rotation rate (radians/sec)
%% Create figure
figure('Color', space_color);
hold on;
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
% Turn off the normal axes
set(gca, 'NextPlot','add', 'Visible','off');
axis equal;
axis auto;
% Set initial view
view(0,30);
axis vis3d;
%% Create wireframe globe
% Create a 3D meshgrid of the sphere points using the ellipsoid function
[x, y, z] = ellipsoid(0, 0, 0, erad, erad, prad, npanels);
globe = surf(x, y, -z, 'FaceColor', 'none', 'EdgeColor', 0.5*[1 1 1]);
%% Texturemap the globe
% Load Earth image for texture map
cdata = imread(image_file);
% Set image as color data (cdata) property, and set face color to indicate
% a texturemap, which Matlab expects to be in cdata. Turn off the mesh edges.
set(globe, 'FaceColor', 'texturemap', 'CData', cdata, 'FaceAlpha', alpha, 'EdgeColor', 'none');
What I wanna do is that when I run the script a figure with the Earth should appear, and while the positions are being caluclated by the runge kutta algorithm it should upload the orbit in real time. But now the figure appears only after the Rk algorithm is being calculated till the end of tspan and the orbit from the figure is already uploaded without intermediate points. What should I do? I've seen on github that others use animatedline and drawnow.
I was thinking about
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
end
But where should I put this line exactly? if I put it in the rk loop it doesn't work and if I put it
% Create figure
figure('Color', space_color);
%%
orbit=animatedline;
addpoints(orbit,y(1,:),y(2,:),y(3,:));
drawnow
it first displays a figure with the orbit but not by intermediate points and then a different figure with the Earth ,while the orbit and the Earth should be in the same figure.
You are using animatedline in a wrong way.
The line:
orbit = animatedline;
should be placed before the loop that calculates the points, and the lines:
addpoints(orbit,y(1,i),y(2,i),y(3,i));
drawnow
should be placed within it, to add one (or several) points to the line on each iteration. But, a better approach, would be to first calculate all the orbit and then use a loop for the animation. This way you have more control over the rate of the animation. Here is a small example using your case:
orbit = animatedline;
for k = 1:size(y,2)
addpoints(orbit,y(1,k),y(2,k),y(3,k));
drawnow
end
Alternative option
Don't use animated line just keep updating the data in the plot. Here is a simple workout for this:
% create a sphere with earth map on it:
set(gcf,'Color','k')
earth = imread('earth.jpg');
[X,Y,Z] = sphere(50);
warp(-X,Y,-Z,earth)
axis off
view(-46,17)
% set an animation of a simple orbit:
Nframes = 100; % number of steps in the orbit
% calculation of the orbit:
orb = linspace(-pi,pi,Nframes);
x = cos(orb).*1.5;
y = sin(orb);
hold on
% plot the whole orbit invisible, just for setting the axes limits:
tmp = plot(x,y,'Color','none');
p = plot(x(1),y(1),'LineWidth',3,'Color','m'); % plot the first step
hold off
for k = 1:numel(orb)
p.XData = x(1:k); % update the data of the plot
p.YData = y(1:k);
pause(0.05) % delay
end
The result:

Plotting too slow on Matlab

I am having some issues with a code I am writing, simply because it is too long to plot. What I am trying to do is for matlab to plot a series of ellipses filled with colors depending on a specific parameter.
Here is the code I am using:
clearvars -except data colheaders
close all
clc
data(:,15)=data(:,9)*pi/180; % Convers Column 9 (angle of rotation) in rad
data(:,16)=1196-data(:,6); % Reset the Y coordinate axis to bottom left
delta = 0 : 0.01 : 2*pi; % Converts roation angle in rad
theta=45*pi/180; % Sample cutting angle
imax=5352; % Numbers of rows in data sheet
% Define variables for colors
beta=acos(data(1:imax,8)./data(1:imax,7));%./acos(0);
phi=atan(sin(beta).*cos(data(1:imax,15))./(sin(theta)*sin(beta).*sin(data(1:imax,15))+cos(theta)*cos(beta)))/(pi/2);
phi2=phi/2+1/2; % Set phi within 0 and 1 for colormap
gamma=atan((cos(theta)*sin(beta).*sin(data(1:imax,15))-sin(theta)*cos(beta))./...
(sin(theta)*sin(beta).*sin(data(1:imax,15))+cos(theta)*cos(beta)))/(pi/2);
gamma2=gamma+1/2; % Set gamma between 0 and 1 for colormap
cm = colormap(jet) ; % returns the current color map
% Sort and get their index to access the color array
[~,idx] = sort(phi);
for i=1:imax
x = data(i,7)/2 * cos(delta) * cos(data(i,15)) - data(i,8)/2 * sin(delta) * sin(data(i,15)) + data(i,5);
y = data(i,8)/2 * sin(delta) * cos(data(i,15)) + data(i,7)/2 * cos(delta) * sin(data(i,15)) + data(i,16);
colorID1 = max(1, sum(phi2(i) > [0:1/length(cm(:,1)):1]));
colorID2 = max(1, sum(gamma2(i) > [0:1/length(cm(:,1)):1]));
ColorMap1(i,:) = cm(colorID1, :); % returns your color
ColorMap2(i,:) = cm(colorID2, :); % returns your color
hold on
% Columns (5,6) are the centre (x,y) of the ellipse
% Columns (7,8) are the major and minor axes (a,b)
% Column 9 is the rotation angle with the x axis
figure(1);
fill(x,y,ColorMap1(i,:),'EdgeColor', 'None');
title('Variation of In-plane angle \phi')
colorbar('SouthOutside')
grid on;
caxis([-90 90])
%text(data(i,5),data(i,16),[num2str(0.1*round(10*acos(0)*180*phi(i)/pi))])
figure(2);
fill(x,y,ColorMap2(i,:),'EdgeColor', 'None');
title('Variation of Out-of-plane angle \gamma')
colorbar('SouthOutside')
grid on;
caxis([-45 45])
%text(data(i,5),data(i,16),[num2str(0.1*round(10*acos(0)*180*gamma(i)/pi))])
% Assigns angle data to each ellipse
end
axis equal;
Maybe someone knows how to make that it doesnt take ages to plot ( i know figure is a bad method, but I want 2 specific colormap for the 2 variables phi and gamma).
Cheers guys
Example data you can use to run the code
data(:,5) = [3 ;5 ;12; 8]; % Centre location X
data(:,6) = [1; -5 ;-2; 4]; % Centre location Y
data(:,7) = [6 ;7;8;9]; % Major Axis a
data(:,8) = [2;3;3;5]; % Minor axis b
data(:,9) = [10;40;45;90]; % Angle of rotation
All you need to do is change imax for 4 instead of 5352 and it should work
Dorian

visualization of light waves superposition in matlab

I wrote some quick code for visualization of superposition of two waves with different amplitudes in space, point source geometry. this works at khanacademy CS platform. http://www.khanacademy.org/cs/superposition/1245709541 but i cant reproduce the exact phenomena in matlab. all i get is a noisy image. Is this something to do with difference in random number generation? I have no idea how different random(0,1)(in JS) and rand(in matlab) are.
here is the matlab code
A wave superposition function for a point x,y on image plane
function S = Super(refamp,objamp,x,y,a,lambda)
r1 = sqrt(a*a+x*x+y*y); %a is in z-axis
S = refamp+(objamp*cos(2*pi*r1/(lambda/(10^6))));
The test script
close all;
clear all;
clc;
a=10; %distance from source to image plane
width = 1024;
height =1024;
im = zeros(width); % the image
x=1;
y=1;
A0 = 3; % amplitude of reference wave
A1 = 1; % amplitude of object wave A0>>A1: A0/A1>=3
lambda = 632; % wavelength in nanometers
% generate the superposition in space width*height at a along z-axis
for y=1:height
for x=1:width
s = Super(A0,A1,x-(width/2),y-(height/2),a, lambda);
r=rand;
if(r<(s/(A0+A1)))
im(x,y) = 1;
end
end
%display the image
figure
imshow(im,[])
title('test image')
The main problem is that your scales are off, so you aren't seeing the interference pattern. If you play around with how big/far everything is, it will work out right and you can see the pattern.
The second problem is that your code would really benefit from vectorization. I've shown this below - doing it this way speeds up the execution dramatically.
function Interference
a=1000 * 10^-9; #% distance from source to image plane
width = 10000 * 10^-9;
height= 10000 * 10^-9;
size = 700;
A0 = 3; %# amplitude of reference wave
A1 = 1; %# amplitude of object wave A0>>A1: A0/A1>=3
lambda = 632 * 10^-9; #% wavelength in nanometers
x=linspace(0,width,size); #% vector from 0 to width
y=linspace(0,height,size); #% vector from 0 to height
[X,Y]=meshgrid(x,y); #% matrices of x and y values at each position
s=Super(A0, A1, X-(width/2), Y-(height/2), a, lambda); #% size-by-size (700x700)
r=rand(size); #% 700x700 matrix of random values on [0 1]
im = zeros(size);
im(r<(s/(A0+A1))) = 1; %# do this all at once instead of pixel-by-pixel
#% display the image
figure
imshow(im,[])
title('test image')
end #% end of function Interference
#% Super is now vectorized, so you can give it a matrix of values for x and y
function S = Super(refamp,objamp,x,y,a,lambda)
r1 = sqrt(a.*a+x.*x+y.*y); #% dot notation: multiply element-wise
S = refamp+(objamp*cos(2*pi*r1/(lambda)));
end #% end of function Super
function i = Interference(width, height, sizeh,sizev,z)
% parameters explained
% width: is the horizontal pixel pitch in microns
% height: is the vertical pixel pitch in microns
% size is the width=height of the CCD in number of pixels
% z is distance from source to image plane
A0 = 3; %# amplitude of reference wave
A1 = 1; %# amplitude of object wave A0>>A1: A0/A1>=3
lambda = 635 * 10^-9; % wavelength in nanometers
%the linspace was wrong
x=linspace(0,width*sizeh,sizeh); % vector from 0 to width of size 'size'
y=linspace(0,height*sizev,sizev); % vector from 0 to height of size 'size'
[X,Y]=meshgrid(x,y); % matrices of x and y values at each position
s=Super(A0, A1, X-((width*sizeh)/2), Y-((height*sizev)/2), z, lambda); % size-by-size (1024x1024)
r=rand(size); % 1024x1024 matrix of random values on [0 1]
%i=s;
im = zeros(size);
im(r<(s/(A0+A1))) = 1; %# do this all at once instead of pixel-by-pixel
i=im;
end % end of function Interference
% Super is now vectorized, so you can give it a matrix of values for x and y
function S = Super(refamp,objamp,x,y,a,lambda)
r1 = sqrt(a.*a+x.*x+y.*y); % dot notation: multiply element-wise
S = refamp+(objamp*cos(2*pi*r1/(lambda)));
end % end of function Super
usage of the function
width = 2.8 * 10^-6;
height= 2.8 * 10^-6; %pixel size
% sizeh = 16; %image size in pixels
% sizev = 16;
sizeh = 1600; %image size in pixels
sizev = 1200;
int_z = 100*10^-3; % z dist in m
% xes1 = 100;
%xes2 = ;
int_im = Interference(width,height,sizeh, sizev,int_z);
int_im = int_im/max(max(int_im)); % normalize
int_im = (int_im-0.5)*2; % enhance visualy
% display the image
figure
imshow(int_im,[])