# Z must be a matrix, not a scalar or vector

3 views (last 30 days)

Show older comments

Hello,

I have run into this problem concerning a code i am writing to find a solution via the Monte Carlo method. Trying to plot my results on a meshgrid or surface, but i keep running into the Z must be a matrix issue. Can anyone spot my problem and give some advice on how to fix it?

Thanks

clear;

clc;

%--Number of simulations--%

n = 100;

sol = linspace(0,1,n);

y = zeros(1,n);

x = zeros(1,n);

%--Plot of the circle--%

figure(1)

clf;

syms p

bc = sin (p);

bc2 = cos (p);

Range = [0 2*pi];

subplot(211);

h = ezplot(bc,bc2,[Range]);

hold on

[X,Y] = meshgrid(-1:0.1:1);

%

Nsamples = 5;

distance = zeros(n,Nsamples);

circle = zeros(n,Nsamples);

delta = 0.1;

% for loop2 = 1:Nsamples

for t=1:n

%--Monte Carlo Random Walk--%

monte = randi(4,1);

if monte == 1

y = y + delta;

elseif monte == 2

y = y - delta;

elseif monte == 3

x = x + delta;

elseif monte ==4

x = x - delta;

end

%--Applying BC if sin is btween pi and 2pi--%

%--Applying it by not allowing y >= 0--%

if y < 0

y = 0;

end

%--Solving for radius to see if BC's are hit--%

radius = sqrt(x.^2 + y.^2);

%--Calculating Theta for the BC--%

theta = atan(y./x);

%--Calcuating the solution with BC's--%

if radius >= 1

sol = sin(theta);

elseif radius <= 0

sol = 0;

end

%--Plotted walk on a circle plot--%

subplot(211);

plot(x,y,'.b');

radius;

sol;

theta;

%--Plotting Surface of Solution--%

figure(2)

mesh(X,Y,sol)

end

##### 0 Comments

### Answers (1)

Mike Hosea
on 26 Mar 2014

### See Also

### Community Treasure Hunt

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

Start Hunting!