why cant i display both the colorbar's title and ticks simultaneously? - matlab

gamma=20;
P=0.1;
N=P.*gamma;
lamdazero=1550;
[lamdapump,lamdasignal] = meshgrid(1540:0.1:1580,1520:0.1:1580);
beta3=0.06;
beta4=-2*10^-4;
c=2*pi*3*10^8;
L=1;
A0=(1./lamdapump) -(1./lamdazero);
B0=(1./lamdapump) -(1./lamdasignal);
Third0=10^-9.*beta3.*(c.^3).*A0.*(B0.^2);
Fourth0=10^-12.*beta4.*(1./2).*c.^4.*(A0.^2).*(B0.^2);
Fourorder=(10^-12).*c.^4.*beta4.*(1/12).*(B0).^4;
deltabeta=Third0+Fourth0+Fourorder;
test2 = deltabeta;
test2(~(deltabeta<=0 & deltabeta>=-4*N)) = nan;
[C,h]=contourf(lamdapump,lamdasignal,test2,[-(4*N):N/2:0],'ShowText','off');
caxis([-8 0]);
xlabel('\lambda_p_u_m_p')
ylabel('\lambda_s_i_g_n_a_l')
title('Contour representing linear phase mismatch in terms of pump and signal wavelength ')
colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'})
h2=colorbar;
HandleOfTitle = get(h2,'Title');
set(HandleOfTitle,'String','\Delta \beta (\gamma P_F_W_M)');
%If i remove the color yticklabel i get my colorbar title and viceversa
%need to know what to do
%The code works just fine

You are creating two colorbars, the second overwrites the first.
colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'})
Creates a colorbar.
h2=colorbar;
Creates another colorbar and removes the first. Get the handle from the first call and remove the second:
h2 = colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'});
Then use the handle to set the title as before.

Related

Title over a group of subplots

I want a figure with six plots inside; I split it with subplots. For example
for i = 1:12
subplot(3,4,i)
plot(peaks)
title(['Title plot ',num2str(i)])
end
I would like to add two global titles, let's say a global title for the six plots on the left hand side and another title for the six other plots on the right hand side.
I don't have 2018b version, so I cannot use sgtitle('Subplot Title');. Is it possible use suptitle('my title'); somehow?
I can use text() but resizing the window, the two labels move.
You can use annotation for that, with the location of subplots 1 and 3:
for k = 1:12
sp(k) = subplot(3,4,k);
plot(peaks)
title(['Title plot ',num2str(k)])
end
spPos = cat(1,sp([1 3]).Position);
titleSettings = {'HorizontalAlignment','center','EdgeColor','none','FontSize',18};
annotation('textbox','Position',[spPos(1,1:2) 0.3 0.3],'String','Left title',titleSettings{:})
annotation('textbox','Position',[spPos(2,1:2) 0.3 0.3],'String','Right title',titleSettings{:})
I did not test this, but you can get the handle to a subplot object and then perform the title method on this handle. I would also suggest to then apply the title after the loop.
CODE
for k = 1:12
h(k) = subplot(3, 4, i)
plot(peak)
end
title(h(1), 'Left side')
title(h(8), 'Right side') % find out the right index yourself
Remark:
Do not use i or j as iteration variable for they are already defined in the namespace of MATLAB as imaginary unit.

Graph Legend MATLAB For Loop

I've got a lab where I need to first derrive a transfer function for a fourth order mass spring damper system, then plot this for a 200N step response.
The dashpot damping coefficient is a variable and we are to plot a range of values graphically and choose the optimium value i.e (the one closest to a critically damped response).
I have all of the above tasks working fully as expected, and maybe I'm just being dumb here but I can't get the graph legend to behave as desired.
I'd ideally like it to say "B="Current Value of B for that itteration of the loop.
%Initialisations
close all;format short g;format compact;clc;clear;
k1=500000;
k2=20000;
m1=20;
m2=400;
opt=stepDataOptions('StepAmplitude',200);
for (b = [1000:1000:15000])
Hs = tf([b k2],[(m1*m2) (b*(m1+m2)) (k2*(m1+m2)+k1*m2) (b*k1) (k1*k2)]);
hold on;
stepplot(Hs,opt)
title("Shock Absorber Performance to Step Input");
ylabel("Force (N)");
legend;
hold off;
end
Thanks in advance :)
Although not such a clean solution, this will work:
close all;format short g;format compact;clc;clear;
k1=500000;
k2=20000;
m1=20;
m2=400;
opt=stepDataOptions('StepAmplitude',200);
% initialize a cell array that will hold the labels
labels = {};
for (b = [1000:1000:15000])
Hs = tf([b k2],[(m1*m2) (b*(m1+m2)) (k2*(m1+m2)+k1*m2) (b*k1) (k1*k2)]);
hold on;
stepplot(Hs,opt)
title("Shock Absorber Performance to Step Input");
ylabel("Force (N)");
hold off;
% set the label name, with the value for b
labels{end+1} = ['B = ' num2str(b)];
end
% create the legend with the labels
legend(labels)

Modify multiple XTick values at once

I want to make a matrix of scatterplots in Matlab (version R2014b), and have only two ticks (minimum and maximum) for each x and y axis because the real world example has more plots and that will be easier to read. Here is an example, and as you can see, the second for loop isn't working as intended to edit the ticks. Also, is there a way to set this without a for loop?
% Example data
example = [ -5.2844 5.0328 307.5500
-12.0310 5.1611 237.9000
-15.9510 7.5500 290.7600
-11.5500 13.6850 285.8400
-1.9356 9.4700 273.2600
-9.2622 4.7456 232.6000
-6.5639 5.2272 265.3800
-4.4795 14.8320 281.1300
-2.1474 13.0690 288.7300
-3.7342 11.7450 265.2200
-11.9040 10.9660 286.5700
-2.1789 6.7442 258.9700
-2.8316 11.8210 281.7500
-2.6170 7.4740 244.8600
-6.8770 1.6623 116.9800
-10.2210 5.7575 300.2200
-3.9430 5.9715 253.6000
-3.3690 5.6530 230.9700
2.6090 3.2750 236.8700
-5.1430 8.4060 273.9600
-7.9360 2.7855 254.8200
-2.8665 2.0241 176.0600
-0.0960 3.3165 228.6800
-8.8465 10.3240 289.2100
-8.1930 16.4070 289.7000
-6.5840 13.4010 283.2600
2.2405 8.4625 270.1000
-2.2505 7.5555 285.9100
-4.6955 6.2985 279.2000
-0.7610 12.5210 283.2000
-0.7510 9.9470 279.9100
1.7120 8.5990 285.5700
-0.6245 7.6905 251.9100
-19.2320 6.8545 306.2700
-4.1255 9.8265 298.2000
2.9486 3.8881 250.2100
1.7333 5.5000 240.7300
-6.5881 3.9152 234.3800
-7.9543 8.0771 276.8000
-6.9641 8.8573 284.2800
-10.3280 7.4768 291.8700
-8.0818 5.1250 250.6600
-10.1490 3.9427 271.0000
-2.7786 3.7673 213.6500
-14.5410 11.1500 288.9100
-6.8118 11.0210 280.2000
-2.6459 6.5127 213.2600
1.4036 4.2023 253.9400
-5.0014 9.3900 267.0600
-9.7382 12.0990 290.8800]
% Labels for data
data_labels = {'Variable1','Variable2',...
'Variable3'};
% Make scatterplot matrix with histogram on diagonal
figure()
[H,AX]= plotmatrix(example(:,:));
% label the axes of the plots (rotated) works fine
for i = 1:length(AX)
ylabel(AX(i,1),data_labels{i},'Rotation',0,'HorizontalAlignment','right',...
'FontSize',12);
xlabel(AX(end,i),data_labels{i},'Rotation',60,'HorizontalAlignment','right',...
'FontSize',12);
end
% Set ticks (not working yet)
NumTicks = 2;
for i = 1:length(AX)
L = get(AX(i,i),'XLim');
set(AX(i,i),'XTick',linspace(L(1),L(2),NumTicks));
% set y ticks here too
end
You are incorrectly using i or both subscripts when indexing into AX.
AX(i) % Rather than AX(i,i)
Also, it's better to use numel than length and use a variable rather than i as your loop variable (since that's a MATLAB built-in for 0 + 1i). Also, you can use a single linear index into AX rather than specifying row and column subscripts.
for k = 1:numel(AX)
L = get(AX(k),'XLim');
set(AX(k),'XTick',linspace(L(1),L(2),NumTicks));
end
If you want to do this witnout a loop, you could technically do it using cellfun and the fact that you can set the same property in multiple plot objects using the following syntax
set(array_of_plot_handles, {'Property'}, array_of_values_to_set)
So applied to your problem, it would be something like
% Get all XLims as a cell array
oldlims = get(AX, 'XLim');
% Compute the new xlims
newlims = cellfun(#(x)linspace(x(1), x(2), NumTicks), oldlims, 'UniformOutput', false);
% Now set the values
set(AX, {'XTick'}, newlims);
Or if you really want it to be one line
set(AX, {'XTick'}, cellfun(#(x)linspace(x(1),x(2),NumTicks), get(AX, 'Xlim'), 'UniformOutput', false))

Matlab get vector of specific pixels

I am pretty new to Matlab and encountered a problem when working with images.
I want to get a pixel that is in a specific colour (blue) in the following image:
image
My current code looks something like this:
function p = mark(image)
%// display image I in figure
imshow(image);
%// first detect all blue values higher 60
high_blue = find(image(:,:,3)>60);
%cross elements is needed as an array later on, have to initialize it with 0
cross_elements = 0;
%// in this iteration the marked values are reduced to the ones
%where the statement R+G < B+70 applies
for i = 1:length(high_blue)
%// my image has the size 1024*768, so to access the red/green/blue values
%// i have to call the i-th, i+1024*768-th or i+1024*768*2-th position of the "array"
if ((image(high_blue(i))+image(high_blue(i)+768*1024))<...
image(high_blue(i)+2*768*1024)+70)
%add it to the array
cross_elements(end+1) = high_blue(i);
end
end
%// delete the zero element, it was only needed as a filler
cross_elements = cross_elements(cross_elements~=0);
high_vector = zeros(length(cross_elements),2);
for i = 1:length(cross_elements)
high_vector(i,1) = ceil(cross_elements(i)/768);
high_vector(i,2) = mod(cross_elements(i), 768);
end
black = zeros(768 ,1024);
for i = 1:length(high_vector)
black(high_vector(i,2), high_vector(i,1)) = 1;
end
cc = bwconncomp(black);
a = regionprops(cc, 'Centroid');
p = cat(1, a.Centroid);
%// considering the detection of the crosses:
%// RGB with B>100, R+G < 100 for B<150
%// consider detection in HSV?
%// close the figure
%// find(I(:,:,3)>150)
close;
end
but it is not optimized for Matlab, obviously.
So i was wondering if there was a way to search for pixels with specific values,
where the blue value is larger than 60 (not hard with the find command,
but at the same time the values in the red and green area not too high.
Is there a command I am missing?
Since English isn't my native language, it might even help if you gave me some suitable keywords for googling ;)
Thanks in advance
Based on your question at the end of the code, you could get what you want in a single line:
NewImage = OldImage(:,:,1) < SomeValue & OldImage(:,:,2) < SomeValue & OldImage(:,:,3) > 60;
imshow(NewImage);
for example, where as you see you provide a restriction for each channel using logical operators, that you can customize of course (eg. using | as logical OR). Is this what you are looking for? According to your code you seem to be looking for specific regions in the image like crosses or coins is that the case? Please provide more details if the code I gave you is completely off the track :)
Simple example:
A = imread('peppers.png');
B = A(:,:,3)>60 & A(:,:,2)<150 & A(:,:,1) < 100;
figure;
subplot(1,2,1);
imshow(A);
subplot(1,2,2)
imshow(B);
Giving this:

MATLAB - Labeling Curves During Iteration

I want to show the p value that was used to generate each curve next to each of the curves plotted. Note that since there is a plot of E and -E, the same p value should be next to both. I've been attempting this for a while and I have not come across anything super useful.
t = -3.1;%coupling
a = 1;%distance between r1 and r3
n = 5;%latice vector span in a1 direction
m = 1;%latice vector span in a2 direction
i = -7;%unique axial vector t_hat direction
j = 11;%unique axial vector c_hat direction
max_p = abs((n*(i+j/2)-j*(m+n/2)));%# of unique p values
La = sqrt(3)*sqrt(m^2+n*m+n^2)*a/gcd(2*n+m,2*m+n);%unit cell length
C = sqrt(n^2+n*m+m^2);%circumference of the nanotube
hold on;
for p=0:1:max_p
kt = -pi/La:.05:pi/La;
kc = 2*pi*p/C;
ka1 = kc*a*.5*(2*n+m)/C + kt*a*sqrt(3)*.5*m/C;
ka2 = kc*a*.5*(n+2*m)/C - kt*a*sqrt(3)*.5*n/C;
E = abs(t+t*exp(1i*ka2)+t*exp(1i*ka1));
title_ = sprintf('(%d,%d) Carbon Nanotube Dispersion Diagram',n,m);
title(title_);
xlabel('k_{t}a');
ylabel('Energy (eV)');
plot(kt,E);
plot(kt,-E);
end
There is a command named text that writes comments into the figures,
http://www.mathworks.se/help/techdoc/ref/text.html
with if you can't solve it with that and the to string operation i misunderstood the question
First, do you need to plot both E and -E? Since these are the same except for their sign you don't really add any information to the plot by having -E there as well. However, if you do need both lines, then just construct an array of strings for the legend, during the loop, which has each string included twice (once for E and once for -E).
... Initial calculations ...
hold on;
for p=0:1:max_p
kt = -pi/La:.05:pi/La;
kc = 2*pi*p/C;
ka1 = kc*a*.5*(2*n+m)/C + kt*a*sqrt(3)*.5*m/C;
ka2 = kc*a*.5*(n+2*m)/C - kt*a*sqrt(3)*.5*n/C;
E = abs(t+t*exp(1i*ka2)+t*exp(1i*ka1));
plot(kt,E);
plot(kt,-E);
% Construct array containing legend text
legend_text{2*(p+1)-1} = strcat('p=', num2str(p));
legend_text{2*(p+1)} = strcat('p=', num2str(p));
end
title_ = sprintf('(%d,%d) Carbon Nanotube Dispersion Diagram',n,m);
title(title_);
xlabel('k_{t}a');
ylabel('Energy (eV)');
legend(legend_text)
I am sure there is a more elegant way of constructing the legend text, but the above code works. Also, notice that I moved the calls to xlabel, ylabel and title to outside of the loop. This way they are only called once and not for each iteration of the loop.
Finally, you need to take care to ensure that each iteration of the loop plots with a different line colour or line style (see edit below). You could colour/style each pair of E and -E lines the same for a given iteration of the loop and just display the legend for E (or -E), which would obviously halve the number of legend entries. To do this you will need to hide one of line's handle visibility - this prevents it from getting an item in the legend. To do this use the following in your loop:
plot(kt, E);
plot(kt,-E, 'HandleVisibility', 'off');
% Construct array containing legend text
legend_text{p+1} = strcat('p=', num2str(p));
Finally, it is best to include clear all at the top of your Matlab scripts.
Edit: To have each plotted line use a different colour for each iteration of your loop use something like the following
... initial calculations ...
cmap = hsv(max_p); % Create a max_p-by-3 set of colors from the HSV colormap
hold on;
for p = 0:1:max_p
plot(kt, E, 'Color', cmap(p,:)); % Plot each pair of lines with a different color
plot(kt, -E, 'Color', cmap(p,:));
end