coloring specific point according to a given parameter [closed] - matlab

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am new to matlab coding and I know it's simple that's why I'm trying to plot 2D datas read from a file,but I'm stuck,with my following code I'm reading the x y coordinates and trying to plot specific point with specific indexing according to given criteria ( which is p in my case I won't go too much into details), all I want to know is how can I modify the code so that I can give the correct index to the point that I want to color(i.e when the condition is satisfied plot this specific points with blue or watever),here is my code :
M=load('data1.XYZ');
x=M(:,1); %all x coordinates
y=M(:,2); %all y coordinates
xA=M(1:400,1); % x of particles A
yA=M(1:400,2); % y of particles A
xB=M(401:800,1); % x of particles B
yB=M(401:800,2); % y of particles B
Pos1=[x y]; % read in the x y coordinates
[num1,junk1] = size(Pos1);
PosA=[xA yA]; % read in the x y A coordinates
PosB=[xB yB]; % read in the x y B coordinates
[numA,junkA] = size(PosA);
[numB,junkB] = size(PosB); %no of all B particles
fprintf('Determining Distances between particles...\n');
r = zeros(numA,1);
psil_avg=0.0+0.0i;
psir_avg=0.0+0.0i;
for m=1:numA
for n=1:numA
cnt_l=0;
psi_l=0.0+0.0i;
if(m~=n)
r(m,n)=norm(PosA(m,:)-PosA(n,:));
if(r(m,n)< 1.44)
v1=PosA(m,:)-PosA(n,:);
u=[0 1];
dot=v1(:,1).*u(:,1)+v1(:,2).*u(:,2);
N=norm(v1);
cosinus=dot/N;
theta=acos(cosinus);
cnt_l=cnt_l+1;
psi_l=psi_l+(cos(theta)+6.0i*sin(theta));
psil_avg=psi_l/cnt_l;
for k=1:numA
cnt_r=0;
psi_r=0.0+0.0i;
if(m~k)
r(m,k)=norm(PosA(m,:)-PosA(k,:));
if(r(m,k)< 1.44)
v2=PosA(m,:)-PosA(k,:);
u2=[0 1];
dot2=v2(:,1).*u2(:,1)+v2(:,2).*u2(:,2);
N2=norm(v2);
cosinus2=dot2/N2;
theta2=acos(cosinus);
cnt_r=cnt_r+1;
psi_r=psi_r+(cos(theta2)+6.0i*sin(theta2));
psir_avg=psi_r/cnt_r;
p=sqrt(psi_r*psi_l);
if p > 0.94
% fprintf('bond order parameter is %f\n',p);
plot(xA(n),yA(n),'ro','Markersize',6);
hold on;
else
plot(xA(n),yA(n),'go','Markersize',8);
end
end
end
end
end
end
end
end
if anyone can help I'd be thankful

Use scatter and the following properties:
'MarkerEdgeColor' — Marker edge color
[0 0 1] (blue) (default) | 'auto' | 'none' | three-element RGB vector | string
'MarkerFaceColor' — Marker face color
'none' (default) | 'auto' | three-element RGB vector | string

Your code is a bit hard to read so I will adress this quiestion in general.
If you have groups of coordinates you would like to plot with different colors say X1,Y1 and X2,Y2 you may do the following
figure
plot(X1,Y1,'r*')
hold on
plot(X2,Y2,'b*')
hold off
This will color the first group in red with a dot and the second with blue and a dot.
The hold on, hold off is made to plot more then one plot on a single axis without clearing the previous one.
As suggested in the comments - you should probably try to avoid looping in matlab.

I could not understand your question clearly. Do you mean like this ? For example if I have two plots
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
Do you want different colours say red for 10,blue for 20, green for 30 degrees for both curves ? Is this what you want ? Please specify properly.

Related

How to create a smoother heatmap

I'd like to create a heat map to analyze the porosity of some specimens that I have 3D-printed. the X-Y coordinates are fixed since they are the positions in which the specimens are printed on the platform.
Heatmap:
Tbl = readtable('Data/heatmap/above.csv');
X = Tbl(:,1);
Y = Tbl(:,2);
porosity = Tbl(:,3);
hmap_above = heatmap(Tbl, 'X', 'Y', 'ColorVariable', 'porosity');
The first question is: how can I sort the Y-axis of the plot? since it goes from the lower value (top) to the higher value (bottom) and I need it the other way around.
The second question is: I only have around 22 data points and most of the chart is without color, so I'd like to get a smoother heatmap without the black parts.
The data set is quite simple and is shown below:
X
Y
porosity
74.4615
118.3773
0.039172163
84.8570
69.4699
0.046314637
95.2526
20.5625
0.041855213
105.6482
-28.3449
0.049796110
116.0438
-77.2522
0.045010692
25.5541
107.9817
0.038562053
35.9497
59.0743
0.041553065
46.3453
10.1669
0.036152061
56.7408
-38.7404
0.060719664
67.1364
-87.6478
0.037756115
-23.3533
97.5861
0.052840845
-12.9577
48.6787
0.045216851
-2.5621
-0.2286
0.033645353
7.8335
-49.1360
0.030670865
18.2290
-98.0434
0.024952472
-72.2607
87.1905
0.036199237
-61.8651
38.2831
0.026725885
-51.4695
-10.6242
0.029212058
-41.0739
-59.5316
0.028572611
-30.6783
-108.4390
0.036796151
-121.1681
76.7949
0.031688096
-110.7725
27.8876
0.034619855
-100.3769
-21.0198
0.039070101
-89.9813
-69.9272
NaN
-79.5857
-118.8346
NaN
If you want to assign color to the "black parts" you will have to interpolate the porosity over a finer grid than you currently have.
The best tool for 2D interpolation over a uniformly sampled grid is griddata
First you have to define the X-Y grid you want to interpolate over, and choose a suitable mesh density.
% this will be the number of points over each side of the grid
gridres = 100 ;
% create a uniform vector on X, from min to max value, made of "gridres" points
xs = linspace(min(X),max(X),gridres) ;
% create a uniform vector on Y, from min to max value, made of "gridres" points
ys = linspace(min(Y),max(Y),gridres) ;
% generate 2D grid coordinates from xs and ys
[xq,yq]=meshgrid(xs,ys) ;
% now interpolate the pososity over the new grid
InterpolatedPorosity = griddata(X,Y,porosity,xq,yq) ;
% Reverse the Y axis (flip the `yq` matrix upside down)
yq = flipud(yq) ;
Now my version of matlab does not have the heatmap function, so I'll just use pcolor for display.
% now display
hmap_above = pcolor(xq,yq,InterpolatedPorosity);
hmap_above.EdgeColor = [.5 .5 .5] ; % cosmetic adjustment
colorbar
colormap jet
title(['Gridres = ' num2str(gridres)])
And here are the results with different grid resolutions (the value of the gridres variable at the beginning):
Now you could also ask MATLAB to further graphically smooth the domain by calling:
shading interp
Which in the 2 cases above would yield:
Notes: As you can see on the gridres=100, you original data are so scattered that at some point interpolating on a denser grid is not going to produce any meaningful improvment. No need to go overkill on your mesh density if you do not have enough data to start with.
Also, the pcolor function uses the matrix input in the opposite way than heatmap. If you use heatmap, you have to flip the Y matrix upside down as shown in the code. But if you end up using pcolor, then you don't need to flip the Y matrix.
The fact that I did it in the code (to show you how to do) made the result display in the wrong orientation for a display with pcolor. Simply comment the yq = flipud(yq) ; statement if you stick with pcolor.
Additionally, if you want to be able to follow the isolevels generated by the interpolation, you can use contour to add a layer of information:
Right after the code above, the lines:
hold on
contour(xq,yq,InterpolatedPorosity,20,'LineColor','k')
will yield:

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

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

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!

Remove overlapped Circles in MATLAB [duplicate]

This question already has answers here:
Non overlapping randomly located circles
(4 answers)
Closed 5 years ago.
I have written a MATLAB code to be able to visualize some Circles. Please have a look at my below code and the attached figure as the output.
clc;
clear;
close all;
% X and Y of each Center
Xloc = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5];
Yloc = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5];
% Radius of each circle
radius = unifrnd(0,1,[1 numel(Xloc)]);
% Random colours
allColours = rand(numel(Xloc),3);
% Transform the data into position = [left bottom width height]
pos = [Xloc(:)-radius(:) Yloc(:)-radius(:) 2*radius(:)*[1 1]];
% Create and format the axes
H = axes;
hold on;
axis equal;
box on;
set(H,'XTickLabel',[],'YTickLabel',[]);
% Create the circles
for idx = 1:numel(Xloc);
rectangle(...
'Position',pos(idx,:),...
'Curvature',[1 1],...
'FaceColor',allColours(idx,:),...
'EdgeColor','none');
end
The output figure is (Circles' radius is generated randomly, so if you execute the code, you will face with a new output):
As you can see in the figure, there is overlap between circles. I was wondering how can I separate centers from each other to do not overlap each others, and at the same time they keep the original distance (or similar distance) from each other in [Xloc Yloc]
You can try to formulate an optimisation problem:
You have to constrain the minimal distance between the centers based on the desired radii.
You have to minimise the deviations from its desired center location.

How to plot an cylindrical coordinates equation in cartesian [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this equation r=z*cos(theta) and I need to plot it in Cartesian coordinates in Matlab. How can I do this?
First off, the definition of your cylindrical co-ordinates is wrong. Given the azimuthal sweep around the z axis theta as well as the radius of the cylinder r, the Cartesian co-ordinates within a cylinder is defined as:
x = r*cos(theta)
y = r*sin(theta)
z = z
Therefore, you would need to define a grid of co-ordinates for r, theta and z, use these co-ordinates and plug them into the above code, then draw them. I would recommend you use plot3 as you want to plot 3D points in Cartesian space. Also, use meshgrid to define your grid of points.
As such, the radius of a cylinder is (usually) constant when you're drawing it, and theta and z are the quantities you are varying. Let's assume that -2 <= z <= 2 and r = 2. We know that to create a cylinder, we have to sweep around a circle from 0 <= theta <= 2*pi. Therefore, do something like this:
%// Define (r,theta,z)
[theta, z] = meshgrid(0:0.001:2*pi, -2:0.001:2);
r = 2*ones(size(theta));
%// Calculate x and y. z was calculated earlier
x = r.*cos(theta);
y = r.*sin(theta);
%// Plot the points
plot3(x(:), y(:), z(:), 'b.');
grid;
view(-48,60); %// Adjust viewing angle
This is what I get:
You can certainly use more efficient techniques, like what Kamtal has suggested with pol2cart, but you said you wanted the actual Cartesian co-ordinates, and so x, y and z contains those co-ordinates in 3D space for you. I'm assuming you want these for further processing.
Good luck!
n = linspace(-pi,pi,20);
m = linspace(0,1,20);
[theta,z] = meshgrid(n,m);
r = z .* cos(theta);
[X,Y,Z] = pol2cart(theta,r,z);
surf(X,Y,Z)
axis equal
If you change it to r = 1 .* cos(theta); then you will get a cylinder,