Ploting a wave with different colors in the same figure [duplicate] - matlab

This question already has an answer here:
Plotting piecewise function
(1 answer)
Closed 5 years ago.
How can I plot a wave (represented by 1 x N matrix) with different colors in matlab. The range for a specific color can be provided manually.
See the diagram below for the expected output.

Here is a simple option:
x = linspace(-4*pi,4*pi,10000); % some data
y = -sin(x); % some data
N = 4;
py = reshape(y,[],N);
px = reshape(x,[],N);
plot(px,py,'LineWidth',2)
Where y is your vector, and N is the number of pieces you want to distinguish. Note that you have to make sure that y is dividable by N with no remainder.
If you want to set the colors, you can do this with set command:
p = plot(px,py,'LineWidth',2)
cmap = parula(N); % a set of N colors in RGB matrix
set(p,{'color'},mat2cell(cmap,ones(N,1),3))
and you get:

That figure looks like a sine function, so let's just assume that it is for this example. While I don't have MATLAB in front of me right now, what I would probably do is, in an m-file script:
clear all; clc;
functionToPlot = [sin(0 : (pi/2) : (8*pi))]; %This spacing will look very sharp and pointy, so I'd recommend using >>linspace like shown in other answers.
yAxisVector = [-1 : 1 : 1];
for n = 1 : length(functionToPlot)
if rem(functionToPlot(1,n),2) <= pi
plot(functionToPlot(1,n),yAxisVector,'r')
hold on
elseif rem(functionToPlot(1,n),4) <= pi
plot(functionToPlot(1,n),yAxisVector,'g')
hold on
elseif rem(functionToPlot(1,n),6) <= pi
plot(functionToPlot(1,n),yAxisVector,'y')
hold on
elseif rem(functionToPlot(1,n),8) <= pi
plot(functionToPlot(1,n),yAxisVector,'c')
hold on
end
end
This code should give you the function that you pictured in your question. Have you tested a code yet? What code did you test? This link shows an alternative method using RGB values, if you prefer that. Good luck with your project!

Related

Statistical test gives result different than reality?

Let's define X as :
and objects releated to it:
I want to calculation value of function following, and plot it on the same graph with histogram eigenvalues of Y.
After that I want to perform chi2gof test to judge weather those two distributions converge to each other or not. I want to use parameter expected with is designed to compare distributions of function and histogram.
My work so far
clf;
m=8000;
n=10000;
X=randn(m,n);
Y=X*X'/n;
sd=std(X(:));
l=m/n;
eigs=eig(Y);
lp=sd^2*(1+sqrt(l))^2;
lm=sd^2*(1-sqrt(l))^2;
x=linspace(0.00000001,lp,n);
for i = 1:length(x)
if (and(x(i) <= lp, x(i) >= lm))
dv(i) = sqrt((lp-x(i)).*(x(i)-lm))./(2*pi*sd^2*l.*x(i));
else
dv(i) = 0;
end
end
This code fully calculates my function dv. Now to plot it on histogram, and to add sens to it I normalized histogram to have unit area.
hold on;
[h, centres] = hist(eigs, 50);
% normalise to unit area
norm_h = h / (numel(eigs) * (centres(2)-centres(1)));
bar(centres, norm_h);
plot(x, dv, "r");
hold off;
The result from this code is image following:
As we can see the dv line really nicely fits the histogram. We can be almost sure that chi square test for same distribution should output p value very close to 1 (it means that samples are from the same distribution). However code
[h,p,stats] = chi2gof(dv,'Expected',norm_h);
outputs
p =
0
It means that null hypothesis of the same distributions were rejected. My question is - how ? Am I using something incorrectly, or this pvalue is really 0 ?

Plotting an exponential function in matlab

I would like to develop some intuition for this language. Specifically about plotting functions on some interval. Here is a concrete example I am trying to work out. Plot exp(x) over the closed interval [-2,2]. Here exp(x) is Matlab notation for e^x, I think. This is the script based on a guide I just read :
x = [ -2 , 2 ];
y = exp(x);
plot(x,y)
The result is not an exponential curve, but a straight line. What is wrong with this script? And also, if anyone can recommend a good guide for this, I would appreciate it very much. Google results I found only have worked examples.
Two methods of adjusting the number of points plotted (samples) of the function are to either specify the interval between the points or the number of points to be plotted. The plot() function will plot the vectors x and y which will plot the number of points equal to the length of vector x. Similar idea to an Excel sheet scatter plot that is joined with line.
Setting the Interval Between the Plotting Points
X_Minimum = -2;
X_Maximum = 2;
Plotting_Interval = 0.25;
x = (X_Minimum: Plotting_Interval: X_Maximum);
y = exp(x);
plot(x,y,'o-');
title(num2str(Plotting_Interval) + " Interval Between Points");
Setting the Number of Plotting Points
X_Minimum = -2;
X_Maximum = 2;
Number_Of_Points = 18;
x = linspace(X_Minimum,X_Maximum,Number_Of_Points);
y = exp(x);
plot(x,y,'o-');
title(num2str(Number_Of_Points) + " Points Plotted");
Ran using MATLAB R2019b
This is because you only input two point into the function plot():(-2,exp(-2)),(2,exp(2))
.In matlab,the x &y of plot(x,y) are vector of the points you have but not their intervals.

ploting a function under condition with Matlab [duplicate]

This question already has an answer here:
Multiple colors in the same line
(1 answer)
Closed 4 years ago.
I am looking for a solution to this problem:
consider a function f (x) = 2x + 1, with x belonging to [0, 1000]. Draw the representative curve of f as a function of x, so that if ||f (x)|| <3 the representative curve of f is in red color and else represent the curve of f in blue color.
Help me because I am a new user of Matlab software
The code below should do the trick:
% Obtain an array with the desired values
y = myfunc(x);
% Get a list of indices to refer to values of y
% meeting your criteria (there are alternative ways
% to do it
indInAbs = find((abs(y)<3));
indOutAbs = find((abs(y)>=3));
% Create two arrays with y-values
% within the desired range
yInAbs = y(indInAbs);
xInAbs = x(indInAbs);
% Create two arrays with y-values
% outside the desired range
yOutAbs = y(indOutAbs);
xOutAbs = x(indOutAbs);
% Plot the values
figure(1);
hold on;
plot( xInAbs, yInAbs, 'r')
plot( xOutAbs, yOutAbs, 'b')
legend('in abs', 'out abs', 'location', 'best')
There are alternative ways to do it which could be more efficient and elegant. However, this is a quick and dirty solution.
Your threshold cannot be too low, otherwise it has not enough data to plot (if threshold=3) or cannot see the blue part. Here I use 500 such that you can see.
function plotSeparate
clc
close all
k=0
threshold=500
for x=1:0.5:1000
k=k+1
y=f(x)
if abs(y)<threshold
t(k,:)=[x,y];
else
s(k,:)=[x,y];
end
end
plot(s(:,1),s(:,2),'-r',t(:,1),t(:,2),'-b')
end
function y=f(x)
y=2*x+1;
end

MATLAB: scatter plot from where each point has its own color [duplicate]

This question already has answers here:
3D scatter plot with 4D data
(2 answers)
Closed 6 years ago.
Suppose I have a situation as follows:
clc; clear;
n = 1001;
m = 1000;
X = linspace(0,1,n);
Y = linspace(0,1,n);
randcolor = rand(m,3);
colorcode = randi(m,m,m);
For i = 1, ..., n and j = 1, ...,n, I would like to plot the points (X(i),Y(j))'s where the RBG color for (X(i),Y(j)) is randcolor(colorcode(i,j),:). I tried to do this the silly way: first declare
figure; hold on;
then do 2 nested loops, n steps each, and use plot to plot a single point n x n times:
for i = 1:n
for j = 1:n
plot(X(i),Y(j),'Marker','o',...
'MarkerEdgeColor',randcolor(colorcode(i,j),:),...
'MarkerFaceColor',randcolor(colorcode(i,j),:));
end
end
This technically worked but it was slow and MATLAB ate up all of my memory when n was increased. What's a better way to do this please?
p.s. In my actual problem, colorcode isn't actually randomly assigned. Rather, it's assigned based on some divergence criterion for a filled Julia set.
You want to use scatter instead of plot which allows you to specify the size and color of each point individually.
colors = rand(numel(X), 3);
S = scatter(X, Y, 100, colors);

evaluating a self made function for a cector and then plotting in matlab

i have created a function that represents a triangle sign.
this function does not work on vectors. i want to evaluate a vector x:
x=[-2:0.01:2]
and save the answer in vector y, for this purpose i came up with the following code:
for i=1:400, y(i) = triangle(x(i))
after i got the ans i plotted is using plot. in this case it worked ok but i am interested on observing the influence of time shifting and shrinking so when i try to use lets say:
for i=1:200, y(i) = triangle(x(2*i))
i get a vector y not the same length as vector x and i cant even plot them... is there any easy way to achieve it? and how should i plot the answer?
here is my function:
function [ out1 ] = triangle( input1 )
if abs(input1) < 1,
out1 = 1 - abs(input1);
else
out1 = 0;
end
end
y is a different length in each for loop because each loop iterated a different number of times. In the example below, I use the same for loops and plot y2 with the corresponding values of x. i is already defined in matlab so I've changed it to t in the example below.
clear all
x=[-2:0.01:2];
for t=1:400
y(t) = triangle(x(t));
end
for t=1:200
y2(t) = triangle(x(2*t));
end
Or, if you want to see y2 plotted over the same range you can increase the size of x:
clear all
x=[-2:0.01:8];
for t=1:400
y(t) = triangle(x(t));
end
for t=1:400
y2(t) = triangle(x(2*t));
end
plot(x(1:length(y)),y,'r')
hold on
plot(x(1:length(y2)),y2,'b')