Colormap 2D for a scalar - Matlab - matlab

i'm simulating a wave propogation in time and place. i want to make a colormap of its values for every time step, in space. i mean, i want to make a figure of 2 axes (x and y) and displays the wave's values at those points by color (the wave varible is V).
how can i do it?
i'v tried:
for ind1 = 1:length(t)
figure()
trisurf(x1,y1,V(:,ind1),'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
end
but i got a message that z (=V) suppose to be a function and not a scalar.
any suggestions?

I have two options, I don't think they will be perfect, but it might help.
First, interpolate the data onto a rectangular mesh and use contourf:
F=scatteredInterp(x,y,V(:,ind1));
X=linspace(min(x),max(x));
Y=linspace(min(y),max(y));
contourf(X,Y,F(X,Y))
Secondly, use scatter to plot points with varying colour:
scatter(x,y,25,V(:,ind1))
where the 25 controls the size of each marker, you may have to experiment with it.
Hope that gives you some ideas.

i've made a loop that finally works:
clear heart_movie
Vnorm = mat2gray(V(:,1:2000));
x1_new = x1-min(x1)+1;
y1_new = y1-min(y1)+1;
for ind1 = 1:2000
heart = zeros(max(x1_new),max(y1_new));
z = Vnorm(:,ind1);
for ind2 = 1:length(z);
heart(y1_new(ind2),x1_new(ind2))= z(ind2);
end
colormap(jet);
imagesc(flipud(heart));
end

Related

MATLAB: function point_cloud

Question:
Write a function called point_cloud that takes one scalar as an input argument (the function does not have to check the format of the input) and has no output argument.
If it is called like this, point_cloud(100), then it plots 100 points. Each point has a random x coordinate and a random y coordinate, each of which is gotten by a call to randn, which uses a normal distribution with a standard deviation equal to 1. The range of the plot axes should be −5 to 5 in both the x and y dimensions. The grid should be turned off. The points should be plotted and displayed one at a time by calling plot with only one point specified and, following the call of plot, by a call of drawnow, which causes the point to be plotted immediately. The command hold on should be included so that all previous points are retained when a new point is plotted.
Figure 2.41 shows an example view of the plot after point_cloud(100000) has completed its point-by-point plotting on a Mac. (Note that on Windows the points are much larger. Also note that it takes a long time to plot this many points with drawnow. Finally, try zooming in the middle.)
Figure 2.41
My Code:
function point_cloud(N)
hold on
grid off
axis([-5,5,-5,5])
for ii = 1:N
plot(randn(ii));
drawnow;
end
I know this is wrong, but I'm not sure how to solve this problem. Can someone help?
Solved code:
function point_cloud(N)
figure
hold on
grid off
axis([-5,5,-5,5])
x = randn(N,1);
y = randn(N,1);
for ii = 1:N
plot(x(ii),y(ii),'b.');
drawnow;
end
You do not need the for loop at all. And drawing the plot each iteration is very time consuming. How about rather using the scatter function.
figure
hold on
grid off
axis([-5,5,-5,5])
x = randn(N,1);
y = randn(N,1);
scatter(x,y,'b.')
This will be a lot faster.
To add to the other answer, here is the code as a function, with the added functionality that the points are one pixel on Windows as well:
function point_cloud(N)
f = figure;
x = randn(N,1);
y = randn(N,1);
scatter(x,y,1/36,'b.');
f.GraphicsSmoothing = 'off';
grid off
axis([-5,5,-5,5])
axis equal
end
The size of the markers is set with the third parameter of scatter: 1/36. The graphics smoothing of the figure needs to be set to 'off' as well, to make sure that the pixels don't become blurry or lighter.
Here's a 3D version:
function point_cloud3D(N)
f = figure;
x = randn(N,1);
y = randn(N,1);
z = randn(N,1);
scatter3(x,y,z,1/36,'b.');
f.GraphicsSmoothing = 'off';
grid off
axis([-5,5,-5,5,-5,5])
axis square
view(3)
end

Plotting a phase portrait with multiple colors with MATLAB

I want to add something to make my phase portrait more understandable. Nevertheless, I can't find anything (I found this
https://se.mathworks.com/help/matlab/ref/colorspec.html
https://se.mathworks.com/matlabcentral/fileexchange/11611-linear-2d-plot-with-rainbow-color
https://se.mathworks.com/help/symbolic/mupad_ref/linecolortype.html
) but it is not what I need.
I would really like to see the color of the line of the phase portrait changing depending of if it is at the beginning or at the end of the simulation.
I found this idea which seems great :
I don't understand at all what he has done (the code is I suppose written here:
https://blogs.mathworks.com/pick/2008/08/15/colors-for-your-multi-line-plots/ )
but It would be great if I can plot a one line function which color varies depending of the time. If moreover, like on the picture, I can have have a scale on the right: it would be awesome.
So for now, I have that :
data = readtable('test.txt');
figure('Name','Phase' , 'units','normalized','outerposition',[(8/100) (0.3- 16/100) 0.5 0.7]);
hold on
plot(data{:,2},data{:,3}, 'k.', 'LineWidth',1.5 );
plot(data{:,4},data{:,5}, 'r.', 'LineWidth',1.5 );
xL = xlim;
yL = ylim;
line([0 0], yL); %x-axis
line(xL, [0 0]); %y-axis
title(['Phase portrait'])
xlabel('f')
ylabel('f '' ')
hold off
I read the values of the function in a .txt file, and then I plot the 2nd/3rd columns and 4/5th columns. The first column is the time evoluting.
Do you have any idea :)?
Thank you!
There are several ways to go about this to be honest.
However it makes a bit easier if you let us know what your time data is.
Do you plot your time data on the x (or y) axis or is it a different additional data set. Should it be an additional data set then you can consider it like z-data, plotted on the Z-axis or/and as a color.
Below is an example of what you can do by making a 3D plot but displaying it in 2D, this allows you to add the colorbar without too many problems.
x=0:5;
y=0:5;
z=rand(1,6); %random data to simulate your time
xx=[x' x']; %this allows you to plot the data using surf in 3d
yy=[y' y']; %same as for xx
z1=zeros(size(xx)); % we don't need z-data so we're making it a matrix of zeros
zc=[z' z']; %input here your time data values, if x/y then you can just use those instead of z
hs=surf(xx,yy,z1,zc,'EdgeColor','interp') %// color binded to "z" values, choose interp for interpolated/gradual color changes, flat makes it sudden
colormap('hsv') %choose your colormap or make it yourself
view(2) %// view(0,90)
hcb=colorbar; %add a colorbar
I found this, thanks to another user on stackoverflaw.
data = readtable('4ressorspendule.txt');
n = numel(data.Var1);
c = size(data,2);
figure('Name','Phase' , 'units','normalized','outerposition',[(8/100) (0.3 - 16/100) 0.5 0.7]);
for i=1:n
hold on
plot(data{i,2},data{i,3},'.','Color',[1 (1-i/n) 0] ,'MarkerSize',4);
plot(data{i,4},data{i,5},'.','Color',[0 (i/n) (1-i/n)],'MarkerSize',4);
end
xL = xlim;
yL = ylim;
line([0 0], yL); %x-axis
line(xL, [0 0]); %y-axis
title(['Phase portrait'])
xlabel('f')
ylabel('f '' ')
hold off

Specifying different colour schemes for different orientations of Polarhistogram in MATLAB

Question
When using polarhistogram(theta) to plot a dataset containing azimuths from 0-360 degrees. Is it possible to specify colours for given segments?
Example
In the plot bellow for example would it be possible to specify that all bars between 0 and 90 degrees (and thus 180-270 degrees also) are red? whilst the rest remains blue?
Reference material
I think if it exists it will be within here somewhere but I am unable to figure out which part exactly:
https://www.mathworks.com/help/matlab/ref/polaraxes-properties.html
If you use rose, you can extract the edges of the histogram and plot each bar one by one. It's a bit of a hack but it works, looks pretty and does not require Matlab 2016b.
theta = atan2(rand(1e3,1)-0.5,2*(rand(1e3,1)-0.5));
n = 25;
colours = hsv(n);
figure;
rose(theta,n); cla; % Use this to initialise polar axes
[theta,rho] = rose(theta,n); % Get the histogram edges
theta(end+1) = theta(1); % Wrap around for easy interation
rho(end+1) = rho(1);
hold on;
for j = 1:floor(length(theta)/4)
k = #(j) 4*(j-1)+1; % Change of iterator
h = polar(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
set(h,'color',colours(j,:)); % Set the color
[x,y] = pol2cart(theta(k(j):k(j)+3),rho(k(j):k(j)+3));
h = patch(x,y,'');
set(h,'FaceColor',colours(j,:),'FaceAlpha',0.2);
uistack(h,'down');
end
grid on; axis equal;
title('Coloured polar histogram')
Result

How to overlay histograms in matlab

I have multiple histograms that I would like to overlay on top of each other but I don't know how to do it. I found the code below but I don't know how to modify it to run on a loop instead of just two histograms.
data1 = randn(100,1); % data of one size
data2 = randn(25, 1); % data of another size!
myBins = linspace(-3,3,10); % pick my own bin locations
% Hists will be the same size because we set the bin locations:
y1 = hist(data1, myBins);
y2 = hist(data2, myBins);
% plot the results:
figure(3);
bar(myBins, [y1;y2]');
title('Mixed size result');
or what is a better way of comparing histograms if they are more than 10 or 20.
Your question is very general. Firstly I do not understand why you insist on a for loop.
Personally I don't like the included bar plot. It quickly gets messy (especially since the bars are not at the "original" location)
If you got a lot of histograms I would consider a stairstep plot as it doesn't fill the plot area so much. Or you could come up with your own - eg using transparent patches.
If it get's lots of curves there are many ways to visualize them google for "multivariate visualization" and be amazed. One of the most amusing ways would be Chernoff faces.
it's much easier now:
histogram(data1, myBins);
hold on;
histogram(data2, myBins);
You could do the following, although it's not the only way:
data = cell(1, N);
y = cell(1, N);
yBar = zeros(N, 10);
for i=1:N
data{1, i} = randn(10*round(rand(1,1)), 1);
y{1, i} = hist(data{1, i}, myBins);
yBar(i, :) = y{1, i};
end
yBar = yBar';
figure(3);
bar(myBins, yBar);
title('Mixed size result');
Using the y cell is not obligatory of course, I left it there to actually show what's happening.
I would suggest this. It's simple and does not require for loops:
bar([y1.' y2.'],'stacked')
Here's a way that was useful to me:
I'm plotting a histogram for each column of the matrix ao.
The code was:
for i = 1:size(ao,2)
[h, y] = hist(ao(:,i), linspace(-5,10,100));
h = i + (0.95./max(h(:))) .* h;
barh(y, h, 'BarWidth', 1, 'BaseValue', i, 'LineStyle', 'none');
hold on;
end
grid;
Note that just changing barh to bar will give the same thing but going up-down instead of left-right (i.e. the figure rotated by 90° anti-clockwise).

Two time series plots and shading between them...MATLAB

I am using MATLAB to plot two lines of a time series... (a min and max line)
I have the points converging at a single point at the end of the data.
I am trying to fill the area in between the lines and then plot other lines on top of the shaded area.
Here is my problem:
When I use "fill" it does exactly what I want it to do...but it draws a line from the last point of the data back to the initial data point. How do I get rid of it?
Here is a very vague sketch of my 2 examples:
The line below the graph is what I am talking about...
Any ideas how to avoid that?
Thanks!
I guess that you create the fill with
fill([xData1;xData2],[yData1;yData2])
where xData1 is a n-by-1 array of x-data for your first curve. This will lead to a weirdly-shaped polygon because the 'corners' of the polygon are not properly ordered.
Instead, you should do
fill([xData1;xData2(end:-1:1)],[yData1;yData2(end:-1:1])
i.e. flip the order of one of the two data sets.
As #Jonas explained (beat me to it), you need to properly order the data of the two time-series. Let me add an example to that:
%# first series
x1 = linspace(pi/4, 5*pi/4, 100);
y1 = cos(x1);
%# second series
x2 = linspace(pi/4, 5*pi/4, 100);
y2 = sin(x2);
subplot(121), fill([x1 x2], [y1 y2], 'r')
subplot(122), fill([x1 fliplr(x2)], [y1 fliplr(y2)], 'r')
hold on
plot(x1,y1, 'Color','b', 'LineWidth',3)
plot(x2,y2, 'Color','g', 'LineWidth',3)