Why is the scatter Circle Color not resulting in a rainbow? - matlab

I am trying to follow this example from Matlab about coloring scatter points as a rainbow, while the x-position of the points is progressing towards the right side.
Here under "Vary Circle Color":
https://de.mathworks.com/help/matlab/ref/scatter.html
x = linspace(0,3*pi,200);
y = cos(x) + rand(1,200);
c = linspace(1,10,length(x));
scatter(x,y,[],c)
While c as a variable goes from 1 to 20 with 200 interpolations. I am trying to replicate this for my piece of code, but I keep getting random color and the x-axis isn't matching the rainbow distribution as this:
g = 6;
pt_x = [0, g, -g];
pt_y = [g, -g, -g];
sz = 10;
loop = 100;
% var(1, loop) = 0;
% c = linspace(-10,10,length(var));
% c = 1:loop;
c = -loop/2:1:loop/2 -1;
rand_x = randi([-g,g],1,1);
rand_y = randi([-g,g],1,1);
for i = 1:loop
r = randi([1,3],1,1);
x1 = (rand_x + pt_x(r)) / 2;
y1 = (rand_y + pt_y(r)) / 2;
seq_x(1, i) = x1;
seq_y(1, i) = y1;
rand_x = x1;
rand_y = y1;
end
scatter(seq_x, cos(seq_x),[],c, 'filled');
What am I missing here exactly? I would appreciate any help!
Expected to get a rainbow pattern
It resulted in a random pattern

Related

Using the if Statement in a for Loop in MATLAB

I am working on a project and my aim is to color and 20 randomly generated lines of all fixed length, then count all lines crossing y=0 and color them green else color them blue.
I have come up with the code below but it doesn't work well in the if statement.
Can someone please have at look? Thank you if you can help!
Question:
How do I correct the if statement to display all the lines and count those lines crossing y = 0?
clear
clc
L = 1.5;
a = -5;
b = 5;
GLines = 0:5:5;
m = 0;
for i = 1:20
X1 = rand(1,i)*(b-a)+a;
Y1 = rand(1,i)*(b-a)+a;
Angle = rand(1,i)*360;
X2 = L*cosd(Angle) + X1;
Y2 = L*sind(Angle) + X2;
if X1(i) < L/2* sind(Angle)
m = m + 1;
plot([X1(i); X2(i)],[Y1(i); Y2(i)], '-g');
else
plot([X1(i); X2(i)],[Y1(i); Y2(i)], '-b');
end
for j = 1:length(GLines)
axis square
ylim([-5 5]);
xlim([-5 5]);
y = yline(GLines(j));
end
end
disp(m)
If a line crosses zero, the sign of Y1 and Y2 will be opposite, so you can do the following:
clear; clc
L = 1.5;
a = -5;
b = 5;
GLines = 0:5:5;
m = 0;
figure;
hold all;
for i = 1:20
X1 = rand*(b-a)+a;
Y1 = rand*(b-a)+a;
Angle = rand*360;
X2 = L*cosd(Angle) + X1;
Y2 = L*sind(Angle) + Y1;
if Y1*Y2 < 0 % if line crosses zero
m = m + 1;
c = 'g'; % color = green
else
c = 'b'; % color = blue
end
plot([X1; X2],[Y1; Y2],'color',c);
end
axis equal
disp(m)
which gives the follwing plot
and correctly outputs m = 2.

How to implement B-Spline in matrix form?

I am simply trying to draw a cubic B-Spline using the matrix representation given in this paper: http://vision.ucsd.edu/~kbranson/research/bsplines/bsplines.pdf
Specifically, I am trying the to exactly replicate the formula in section 3 (using placement matrix G) of the PDF. But I am not sure where I am going wrong. It keeps producing straight lines. Can anyone point me out what is wrong with the following code (it should run on any version of matlab; its quite simple) ?
% main.m
clc; clear;
n_cpts = 5;
deg = 3;
cpts = randi(30, n_cpts, 2);
n_knots = n_cpts + deg + 1;
knots = 0:(n_knots-1);
ts = knots(deg):0.05:knots(end-deg);
curve = [];
for t = ts(1:end-1)
k = floor(t);
T = [1, t, t^2, t^3];
B = Bi(k);
G = Gi(k, n_cpts);
p = T * B * G * cpts;
curve = [curve; p];
end
scatter(curve(:,1), curve(:,2));
The helper functions
% Bi.m
% The 'B' matrix
function [B] = Bi(i)
B = [[ -(1./6.)*i^3, (1./6.)*(3*i^3 + 3*i^2 - 3*i + 1), -(1./2.)*(i^3)-(i^2)+2./3., (1./2.)*(i+1)^3 ];
[ +(1./2.)*i^2, -(1./2.)*(3*i-1)*(i+1), (1./2.)*(3*i^2 + 4*i), -(1./2.)*(i+1)^2 ];
[ (1./2.)*i, (1./2.)*(3*i+1), -(1./2.)*(3*i+2), (1./2.)*(i+1) ];
[ (1./6.), -(1./2.), (1./2.), -(1./6.) ]];
end
% Gi.m
% The 'G' matrix
function [G] = Gi(i, L)
G = zeros(4, L);
for m = 1:4
for n = 1:L
if n == i+m-3
G(m,n) = 1;
end
end
end
end
My output looks like this:

Active contours with open ends

Does anyone know how to make an open active contour? I'm familiar with closed contours and I have several Matlab programs describing them. I've tried to change the matrix P but that was not enough: My Matlab code is as follows:
% Read in the test image
GrayLevelClump=imread('cortex.png');
cortex_grad=imread('cortex_grad.png');
rect=[120 32 340 340];
img=imcrop(GrayLevelClump,rect);
grad_mag=imcrop(cortex_grad(:,:,3),rect);
% Draw the initial snake as a line
a=300;b=21;c=21;d=307;
snake = brlinexya(a,b,c,d); % startpoints,endpoints
x0=snake(:,1);
y0=snake(:,2);
N=length(x0);
x0=x0(1:N-1)';
y0=y0(1:N-1)';
% parameters for the active contour
alpha = 5;
beta = 10;
gamma = 1;
kappa=1;
iterations = 50;
% Make a force field
[u,v] = GVF(-grad_mag, 0.2, 80);
%disp(' Normalizing the GVF external force ...');
mag = sqrt(u.*u+v.*v);
px = u./(mag+(1e-10)); py = v./(mag+(1e-10));
% Make the coefficient matrix P
x=x0;
y=y0;
N = length(x0);
a = gamma*(2*alpha+6*beta)+1;
b = gamma*(-alpha-4*beta);
c = gamma*beta;
P = diag(repmat(a,1,N));
P = P + diag(repmat(b,1,N-1), 1) + diag( b, -N+1);
P = P + diag(repmat(b,1,N-1),-1) + diag( b, N-1);
P = P + diag(repmat(c,1,N-2), 2) + diag([c,c],-N+2);
P = P + diag(repmat(c,1,N-2),-2) + diag([c,c], N-2);
P = inv(P);
d = gamma * (-alpha);
e = gamma * (2*alpha);
% Do the modifications to the matrix in order to handle OAC
P(1:2,:) = 0;
P(1,1) = -gamma;
P(2,1) = d;
P(2,2) = e;
P(2,3) = d;
P(N-1:N,:) = 0;
P(N-1,N-2) = d;
P(N-1,N-1) = e;
P(N-1,N) = d;
P(N,N) = -gamma;
x=x';
y=y';
figure,imshow(grad_mag,[]);
hold on, plot([x;x(1)],[y;y(1)],'r');
plot(x([1 end]),y(([1 end])), 'b.','MarkerSize', 20);
for ii = 1:50
% Calculate external force
vfx = interp2(px,x,y,'*linear');
vfy = interp2(py,x,y,'*linear');
tf=isnan(vfx);
ind=find(tf==1);
if ~isempty(ind)
vfx(ind)=0;
end
tf=isnan(vfy);
ind=find(tf==1);
if ~isempty(ind)
vfy(ind)=0;
end
% Move control points
x = P*(x+gamma*vfx);
y = P*(y+gamma*vfy);
%x = P * (gamma* x + gamma*vfx);
%y = P * (gamma* y + gamma*vfy);
if mod(ii,5)==0
plot([x;x(1)],[y;y(1)],'b')
end
end
plot([x;x(1)],[y;y(1)],'r')
I've modified the coefficient matrix P in order to handle cases with open ended active contours, but that is clearly not enough.
My image:

Error in evaluating a function

EDIT: The code that I have pasted is too long. Basicaly I dont know how to work with the second code, If I know how calculate alpha from the second code I think my problem will be solved. I have tried a lot of input arguments for the second code but it does not work!
I have written following code to solve a convex optimization problem using Gradient descend method:
function [optimumX,optimumF,counter,gNorm,dx] = grad_descent()
x0 = [3 3]';%'//
terminationThreshold = 1e-6;
maxIterations = 100;
dxMin = 1e-6;
gNorm = inf; x = x0; counter = 0; dx = inf;
% ************************************
f = #(x1,x2) 4.*x1.^2 + 2.*x1.*x2 +8.*x2.^2 + 10.*x1 + x2;
%alpha = 0.01;
% ************************************
figure(1); clf; ezcontour(f,[-5 5 -5 5]); axis equal; hold on
f2 = #(x) f(x(1),x(2));
% gradient descent algorithm:
while and(gNorm >= terminationThreshold, and(counter <= maxIterations, dx >= dxMin))
g = grad(x);
gNorm = norm(g);
alpha = linesearch_strongwolfe(f,-g, x0, 1);
xNew = x - alpha * g;
% check step
if ~isfinite(xNew)
display(['Number of iterations: ' num2str(counter)])
error('x is inf or NaN')
end
% **************************************
plot([x(1) xNew(1)],[x(2) xNew(2)],'ko-')
refresh
% **************************************
counter = counter + 1;
dx = norm(xNew-x);
x = xNew;
end
optimumX = x;
optimumF = f2(optimumX);
counter = counter - 1;
% define the gradient of the objective
function g = grad(x)
g = [(8*x(1) + 2*x(2) +10)
(2*x(1) + 16*x(2) + 1)];
end
end
As you can see, I have commented out the alpha = 0.01; part. I want to calculate alpha via an other code. Here is the code (This code is not mine)
function alphas = linesearch_strongwolfe(f,d,x0,alpham)
alpha0 = 0;
alphap = alpha0;
c1 = 1e-4;
c2 = 0.5;
alphax = alpham*rand(1);
[fx0,gx0] = feval(f,x0,d);
fxp = fx0;
gxp = gx0;
i=1;
while (1 ~= 2)
xx = x0 + alphax*d;
[fxx,gxx] = feval(f,xx,d);
if (fxx > fx0 + c1*alphax*gx0) | ((i > 1) & (fxx >= fxp)),
alphas = zoom(f,x0,d,alphap,alphax);
return;
end
if abs(gxx) <= -c2*gx0,
alphas = alphax;
return;
end
if gxx >= 0,
alphas = zoom(f,x0,d,alphax,alphap);
return;
end
alphap = alphax;
fxp = fxx;
gxp = gxx;
alphax = alphax + (alpham-alphax)*rand(1);
i = i+1;
end
function alphas = zoom(f,x0,d,alphal,alphah)
c1 = 1e-4;
c2 = 0.5;
[fx0,gx0] = feval(f,x0,d);
while (1~=2),
alphax = 1/2*(alphal+alphah);
xx = x0 + alphax*d;
[fxx,gxx] = feval(f,xx,d);
xl = x0 + alphal*d;
fxl = feval(f,xl,d);
if ((fxx > fx0 + c1*alphax*gx0) | (fxx >= fxl)),
alphah = alphax;
else
if abs(gxx) <= -c2*gx0,
alphas = alphax;
return;
end
if gxx*(alphah-alphal) >= 0,
alphah = alphal;
end
alphal = alphax;
end
end
But I get this error:
Error in linesearch_strongwolfe (line 11) [fx0,gx0] = feval(f,x0,d);
As you can see I have written the f function and its gradient manually.
linesearch_strongwolfe(f,d,x0,alpham) takes a function f, Gradient of f, a vector x0 and a constant alpham. is there anything wrong with my declaration of f? This code works just fine if I put back alpha = 0.01;
As I see it:
x0 = [3; 3]; %2-element column vector
g = grad(x0); %2-element column vector
f = #(x1,x2) 4.*x1.^2 + 2.*x1.*x2 +8.*x2.^2 + 10.*x1 + x2;
linesearch_strongwolfe(f,-g, x0, 1); %passing variables
inside the function:
[fx0,gx0] = feval(f,x0,-g); %variable names substituted with input vars
This will in effect call
[fx0,gx0] = f(x0,-g);
but f(x0,-g) is a single 2-element column vector with these inputs. Assingning the output to two variables will not work.
You either have to define f as a proper named function (just like grad) to output 2 variables (one for each component), or edit the code of linesearch_strongwolfe to return a single variable, then slice that into 2 separate variables yourself afterwards.
If you experience a very rare kind of laziness and don't want to define a named function, you can still use an anonymous function at the cost of duplicating code for the two components (at least I couldn't come up with a cleaner solution):
f = #(x1,x2) deal(4.*x1(1)^2 + 2.*x1(1)*x2(1) +8.*x2(1)^2 + 10.*x1(1) + x2(1),...
4.*x1(2)^2 + 2.*x1(2)*x2(2) +8.*x2(2)^2 + 10.*x1(2) + x2(2));
[fx0,gx0] = f(x0,-g); %now works fine
as long as you always have 2 output variables. Note that this is more like a proof of concept, since this is ugly, inefficient, and very susceptible to typos.

Finding correct index value for matrix in Matlab using meshgrid

I'm trying to build make a code where an equation is not calculated for some certain values. I have a meshgrid with several values for x and y and I want to include a for loop that will calculate some values for most of the points in the meshgrid but I'm trying to include in that loop a condition that if the points have a specified index, the value will not be calculated. In my second group of for/if loops, I want to say that for all values of i and k (row and column), the value for z and phi are calculated with the exception of the specified i and k values (in the if loop). What I'm doing at the moment is not working...
The error I'm getting is:
The expression to the left of the equals sign is not a valid target for an assignment.
Here is my code at the moment. I'd really appreciate any advice on this! Thanks in advance
U_i = 20;
a = 4;
c = -a*5;
b = a*10;
d = -20;
e = 20;
n = a*10;
[x,y] = meshgrid([c:(b-c)/n:b],[d:(e-d)/n:e]');
for i = 1:length(x)
for k = 1:length(x)
% Zeroing values where cylinder is
if sqrt(x(i,k).^2 + y(i,k).^2) < a
x(i,k) = 0;
y(i,k) = 0;
end
end
end
r = sqrt(x.^2 + y.^2);
theta = atan2(y,x);
z = zeros(length(x));
phi = zeros(length(x));
for i = 1:length(x)
for k = 1:length(x)
if (i > 16 && i < 24 && k > 16 && k <= length(x))
z = 0;
phi = 0;
else
z = U_i.*r.*(1-a^2./r.^2).*sin(theta); % Stream function
phi = U_i*r.*(1+a^2./r.^2).*cos(theta); % Velocity potential
end
end
end
The original code in the question can be rewritten as seen below. Pay attention in the line with ind(17:24,:) since your edit now excludes 24 and you original question included 24.
U_i = 20;
a = 4;
c = -a*5;
b = a*10;
d = -20;
e = 20;
n = a*10;
[x,y] = meshgrid([c:(b-c)/n:b],[d:(e-d)/n:e]');
ind = find(sqrt(x.^2 + y.^2) < a);
x(ind) = 0;
y(ind) = 0;
r = sqrt(x.^2 + y.^2);
theta = atan2(y,x);
ind = true(size(x));
ind(17:24,17:length(x)) = false;
z = zeros(size(x));
phi = zeros(size(x));
z(ind) = U_i.*r(ind).*(1-a^2./r(ind).^2).*sin(theta(ind)); % Stream function
phi(ind) = U_i.*r(ind).*(1+a^2./r(ind).^2).*cos(theta(ind)); % Velocity potential