Matlab plots coloring area - matlab-figure

I'm working on this code to get liner power consumption result :
P_out = 0:100;
Po= 130 ;
dP= 4.7 ;
N_TRX=6;
P_max= 20;
p_sleep= 75;
if 0< P_out <= P_max
P = N_TRX*Po+N_TRX*dP*P_out;
else
P=N_TRX* p_sleep;
end
%%%%%
Po= 130 ;
dP= 2.8 ;
N_TRX=6;
P_max= 40;
if 0< P_out <= P_max
P1= N_TRX*Po+N_TRX*dP*P_out;
else
P1=N_TRX* p_sleep;
end
%%%%%
Po= 130 ;
dP= 5.9 ;
N_TRX=2;
P_max= 20;
if 0< P_out <= P_max
P2= N_TRX*(Po+dP*P_out);
else
P_in2=N_TRX* p_sleep;
end
%%%%%
Po= 110 ;
dP= 4.2;
N_TRX=6;
P_max= 20;
if 0< P_out <= P_max_macro
P3= N_TRX*Po+N_TRX*dP*P_out;
else
P3=N_TRX* p_sleep;
end
figure, plot(P_out,P,'b'); hold on, plot(P_out,P1,'g'); hold on, plot(P_out,P2,'r'); hold on,plot (P_out,P3,'y'),hold off
The plot is here:
and I want to fill the area between the lines with colors to get 4 areas colored with its line color.

Here is a way to do this using the area function:
h = area(P_out,[P2;P1-P2;P3-P1;P-P3].');
h(1).FaceColor = 'r';
h(2).FaceColor = 'g';
h(3).FaceColor = 'y';
h(4).FaceColor = 'b';
Which will give you this:
you can also use some nicer colors and transparency:
ax = axes;
col = mat2cell(lines(4),ones(4,1),3);
hold on
h(1) = area(ax,P_out,P);
h(4) = area(ax,P_out,P3);
h(2) = area(ax,P_out,P1);
h(3) = area(ax,P_out,P2);
set(h,{'FaceColor'},col)
set(h,'FaceAlpha',0.6)
hold off
to get this:

Related

Matlab visualization

I used this link to walk through FDTD code and write it for myself to practice.
https://www.youtube.com/watch?v=y7hJAhKp2d8
This is the code that I wrote (its not verbatim, but extremely similar). When I run the program, I am told that "Field amplitude is too small to visualize properly." I don't understand why. As far as I understand Matlab (I'm very new to it), I am scaling the graph on my own. There is a function called draw1d that is in a protected file here: http://emlab.utep.edu/ee5390fdtd.htm
How should I fix this?
%FDTD1D
%Initailize
close all;
clc;
clear all;
% Units
meters = 1;
seconds = 1;
%Fundamental constants
c0 = 3e8 * meters/seconds;
e0 = 8.85e-12 * 1/meters;
u0 = 1.26e-6 * 1/meters;
%Figure Window
figure('Color', 'b');
%%%%%%%
%% FUNAMENTAL CONSTANTS
%%%%%%%%%
%Simple parameters
dz = 5 * meters;
Nz = 200;
dt = 1e-3 * seconds;
STEPS = 1000;
%%%%%%%
%% BUILD DEVICE ON GRID
%%%%%%%%%
%Grid Device - let it be air
ER = ones(1, Nz);
UR = ones(1, Nz);
%%%%%%%
%% Initialize FDTD Parameters
%%%%%%%%%
%Initialize Vectors
mEy = (c0*dt)./ER; %unique update coefficient for each place on the grid
mHx = (c0*dt)./UR; %unique update coefficent again
%%%%%%%
%% Initialize Fields
%%%%%%%%%
%Initialize Fields
Ey = zeros(1, Nz);
Hx = zeros(1, Nz);
%%%%%%%
%% IFDTD LOOP ANALYSIS
%%%%%%%%%
%Actually doing FDTD
for T = 1 : STEPS
%Update H from E
for nz = 1 : Nz - 1
Hx(nz) = Hx(nz) + mHx(nz)*(Ey(nz+1) - Ey(nz))/dz;
end
Hx(Nz) = Hx(Nz) + mHx(Nz)*(0 - Ey(Nz))/dz;
%Update E from H
Ey(1) = Ey(1) + mEy(1) * ( Hx(1) - 0 )/dz;
for nz = 2 : Nz
Ey(nz) = Ey(nz) + mEy(nz) * ( Hx(nz) - Hx(nz-1) )/dz;
end
%Show Status
if ~mod(T, 10)
draw1d(ER, Ey, Hx, dz);
xlim([dz Nz*dz]);
xlabel('z');
title(['Field at step ' num2str(T) ' of ' num2str(STEPS)]);
end
end

Kaczmarz animation

i am asking for help.. I want to animate the Kaczmarz method on Matlab. It's method allows to find solution of system of equations by the serial projecting solution vector on hyperplanes, which which is given by the eqations of system.
And i want make animation of this vector moving (like the point is going on the projected vectors).
%% System of equations
% 2x + 3y = 4;
% x - y = 2;
% 6x + y = 15;
%%
A = [2 3;1 -1; 6 1];
f = [4; 2; 15];
resh = pinv(A)*f
x = -10:0.1:10;
e1 = (1 - 2*x)/3;
e2 = (x - 2);
e3 = 15 - 6*x;
plot(x,e1)
grid on
%
axis([0 4 -2 2])
hold on
plot(x,e2)
hold on
plot(x,e3)
hold on
precision = 0.001; % точность
iteration = 100; % количество итераций
lambda = 0.75; % лямбда
[m,n] = size(A);
x = zeros(n,1);
%count of norms
for i = 1:m
nrm(i) = norm(A(i,:));
end
for i = 1:1:iteration
j = mod(i-1,m) + 1;
if (nrm(j) <= 0), continue, end;
predx = x;
x = x + ((f(j) - A(j,:)*x)*A(j,:)')/(nrm(j))^2;
p = plot(x);
set(p)
%pause 0.04;
hold on;
if(norm(predx - x) <= precision), break, end
end
I wrote the code for this method, by don't imagine how make the animation, how I can use the set function.
In your code there are a lot of redundant and random pieces. Do not call hold on more than once, it does nothing. Also set(p) does nothing, you want to set some ps properties to something, then you use set.
Also, you are plotting the result, but not the "change". The change is a line between the previous and current, and that is the only reason you'd want to have a variable such as predx, to plot. SO USE IT!
Anyway, this following code plots your algorithm. I added a repeated line to plot in green and then delete, so you can see what the last step does. I also changed the plots in the begging to just plot in red so its more clear what is each of the things.
Change your loop for:
for i = 1:1:iteration
j = mod(i-1,m) + 1;
if (nrm(j) <= 0), continue, end;
predx = x;
x = x + ((f(j) - A(j,:)*x)*A(j,:)')/(nrm(j))^2;
plot([predx(1) x(1)],[predx(2) x(2)],'b'); %plot line
c=plot([predx(1) x(1)],[predx(2) x(2)],'g'); %plot it in green
pause(0.1)
children = get(gca, 'children'); %delete the green line
delete(children(1));
drawnow
% hold on;
if(norm(predx - x) <= precision), break, end
end
This will show:

Optimizing for loop in Matlab

I'm writing a "Peak finder" in Matlab. I've never used Matlab or anything similar before this project, so I'm new to "vectorizing" my code. Essentially, the program needs to take a video of molecules and plot circles on the molecules present in each frame of the video. If a molecule is crowded then it gets a red circle, but if it is not crowded it gets a green circle.
My problem is that some of these videos have 2000 frames and my program takes up to ~25 seconds to process a single frame, which is not practical.
Using tic and toc I've found the trouble maker: A for-loop which calls a function that contains a for-loop.
function getPeaks( orgnl_img, processed_img, cut_off, radius )
% find large peaks peaks by thresholding, i.e. you accept a peak only
% if its more than 'threshold' higher than its neighbors
threshold = 2*std2(orgnl_img);
peaks = (orgnl_img - processed_img) > threshold;
% m and n are dimensions of the frame, named peaks
[m, n] = size(peaks);
cc_centroids = regionprops(peaks, 'centroid');
% Pre-allocate arrays
x_centroid = zeros(1, length(cc_centroids));
y_centroid = zeros(1, length(cc_centroids));
for i = 1:length(cc_centroids)
% Extract the x and y components from cc_centroids struct
x_centroid(i) = cc_centroids(i).Centroid(1);
y_centroid(i) = cc_centroids(i).Centroid(2);
row = int64(x_centroid(i));
col = int64(y_centroid(i));
% Assure that script doesnt attempt to exceed frame
if col-2 > 0 && row-2 > 0 && col+2 < m && row+2 < n
region_of_interest = orgnl_img(col-2:col+2,row-2:row+2);
local_intensity = max(region_of_interest(:));
% Do not plot circle when intensity is 'cut off' or lower
if local_intensity > cut_off
dist_bool = findDistance(cc_centroids, x_centroid(i), y_centroid(i), radius);
if dist_bool == 1
color = 'g';
else
color = 'r';
end
plotCircle(color, x_centroid(i), y_centroid(i), radius)
end
end
end
end
And here is the findDistance function which contains another for-loop and determines if the circles overlap:
function dist_bool = findDistance( all_centroids, x_crrnt, y_crrnt, radius )
x_nearby = zeros(1, length(all_centroids));
y_nearby = zeros(1, length(all_centroids));
for i = 1:length(all_centroids)
if all_centroids(i).Centroid(1) < (x_crrnt+2*radius) &&...
all_centroids(i).Centroid(1) > (x_crrnt-2*radius) &&...
all_centroids(i).Centroid(2) < (y_crrnt+2*radius) &&...
all_centroids(i).Centroid(2) > (y_crrnt-2*radius)
x_nearby(i) = all_centroids(i).Centroid(1);
y_nearby(i) = all_centroids(i).Centroid(2);
pts_of_interest = [x_nearby(i),y_nearby(i);x_crrnt,y_crrnt];
dist = pdist(pts_of_interest);
if dist == 0 || dist > 2*radius
dist_bool = 1;
else
dist_bool = 0;
break
end
end
end
end
I think that there must be much improvement to be done here. I would appreciate any advice.
Thanks! :)
UPDATE: Here are the profiler results. The first section of code is the "getPeaks" function
http://i.stack.imgur.com/VaLdH.png
The hold comes from the plot circle function:
function plotCircle( color, x_centroid, y_centroid, radius )
hold on;
th = 0:pi/50:2*pi;
xunit = radius * cos(th) + x_centroid;
yunit = radius * sin(th) + y_centroid;
plot(xunit, yunit, color);
hold off;
end

MATLAB help cropping an image

I am using MATLAB R2012a and I am trying to let the user crop the image WITHOUT the use of the built in function.
here is my code:
[x, y] = ginput(2);
m1 = [x(1), y(1)];
m2 = [x(2), y(2)];
m1 = int16(m1);
m2 = int16(m2);
[m, n] = size(manip);
s1 = (m2(1) - m1(1))+1;
s2 = (m2(2) - m2(2))+1;
temp = zeros([s1, s2],('uint8'));
p1 = 0;
p2 = 0;
for c1 = 1:m
if ((c1 <= m1(2)) && (c1 >= m2(2)))
for c2 = 1:n
if ((c2 <= m1(1)) && (c2 >= m2(1)))
temp(p1, p2) = manip(c1, c2);
end
p2 = p2 + 1;
end
end
p1 = p1 + 1;
end
out = temp;
and here is my result:
Any ideas of what I did wrong, I can's seem to be able to see it. Thanks.
I would imagine your error is here: s2 = (m2(2) - m2(2))+1; should this not be s2 = (m2(2) - m1(2))+1; ?
However you don't need that loop at all:
Iold = rand(300);
%crop 10 pixels off each side
Inew = Iold(11:end - 10, 11: end - 10);
or if you need the images the same size but with zeros where the cropped bits are:
Inew = zeros(size(Iold));
Inew(11:end - 10, 11: end - 10) = Iold(11:end - 10, 11: end - 10);
or to generalize it:
Inew(xmin:xmax, ymin:ymax) = Iold(xmin:xmax, ymin:ymax);

Understanding and Implementing Thinning Algorithm in MATLAB

I am trying to implement my own Thinning Algorithm in Matlab to understand the thinning algorithm. I am following http://fourier.eng.hmc.edu/e161/lectures/morphology/node2.html and implementing my own code, but the result is incorrect.
Here is my code:
%for the sake of simplicity, the outermost pixels are ignored.
for x = 2:1:511
for y = 2:1:511
% if this pixel is not black, then, proceed in.
if (frame2(y,x) > 0)
% the pos(1 to 8) here are for the surrounding pixels.
pos(1) = frame2(y-1,x-1);
pos(2) = frame2(y, x-1);
pos(3) = frame2(y+1, x+1);
pos(4) = frame2(y+1, x);
pos(5) = frame2(y+1, x-1);
pos(6) = frame2(y, x-1);
pos(7) = frame2(y-1, x-1);
pos(8) = frame2(y-1, x);
nonZeroNeighbor = 0;
transitSequence = 0;
change = 0;
for n = 1:1:8
% for N(P1)
if (pos(n) >= 1)
nonZeroNeighbor = nonZeroNeighbor + 1;
end
% for S(P1)
if (n > 1)
if (pos(n) ~= change)
change = pos(n);
transitSequence = transitSequence + 1;
end
else
change = pos(n);
end
end
% also for S(P1)
if ((nonZeroNeighbor > 1 && nonZeroNeighbor < 7) || transitSequence >= 2)
markMatrix(y,x) = 1;
fprintf(1, '(%d,%d) nonzero: %d transit: %d\n', y,x, nonZeroNeighbor, transitSequence);
else %this else here is for the reverse.
end
end
end
end
for x = 2:1:511
for y = 2:1:511
if (markMatrix(y,x) > 0)
frame2(y,x) = 0;
end
end
end
savePath = [path header number2 '.bmp'];
imwrite(frame2, savePath, 'bmp'); %output image here, replacing the original
From the site above, it states the function S(P1) as:
"S(P1): number of 0 to 1 (or 1 to 0) transitions in the sequence (P2, P3, ..., P9)"
For this part, my codes are below "% for S(P1)" and "% also for S(P1)" comments. Am I implementing this function correctly? The output image I got is simply blank. Nothing at all.
For the correct output, I am aware that there is a logical problem. Regarding the site, it states:
When part of the shape is only 2-pixel wide, all pixels are boundary points and will be marked and then deleted.
This problem is to be ignored for now.
I've had a go at the problem and think I managed to get the algorithm to work. I've made several small edits along the way (please see the code below for details), but also found two fundamental problems with your initial implementation.
Firstly, you assumed all would be done in the first pass of step 1 and 2, but really you need to let the algorithm work away at the image for some time. This is typical for iterative morphological steps 'eating' away at the image. This is the reason for the added while loop.
Secondly, your way of calculating S() was wrong; it counted both steps from 0 to 1 and 1 to 0, counting twice when it shouldn't and it didn't take care of the symmetry around P(2) and P(9).
My code:
%Preliminary setups
close all; clear all;
set(0,'DefaultFigureWindowStyle','Docked')
%Read image
frame2 = imread('q1.jpg');
%Code for spesific images
%frame2(:,200:end) = [];
%frame2 = rgb2gray(frame2);
%Make binary
frame2(frame2 < 128) = 1;
frame2(frame2 >= 128) = 0;
%Get sizes and set up mark
[Yn Xn] = size(frame2);
markMatrix = zeros(Yn,Xn);
%First visualization
figure();imagesc(frame2);colormap(gray)
%%
%While loop control
cc = 0;
changed = 1;
while changed && cc < 50;
changed = 0;
cc = cc + 1;
markMatrix = zeros(Yn,Xn);
for x = 2:1:Xn-1
for y = 2:1:Yn-1
% if this pixel is not black, then, proceed in.
if (frame2(y,x) > 0)
% the pos(2 to 9) here are for the surrounding pixels.
pos(1) = frame2(y, x);
pos(2) = frame2(y-1, x);
pos(3) = frame2(y-1, x+1);
pos(4) = frame2(y, x+1);
pos(5) = frame2(y+1, x+1);
pos(6) = frame2(y+1, x);
pos(7) = frame2(y+1, x-1);
pos(8) = frame2(y, x-1);
pos(9) = frame2(y-1, x-1);
nonZeroNeighbor = 0;
transitSequence = 0;
change = pos(9);
for n = 2:1:9
%N()
nonZeroNeighbor = sum(pos(2:end));
%S()
if (double(pos(n)) - double(change)) < 0
transitSequence = transitSequence + 1;
end
change = pos(n);
end
%Test if pixel is to be removed
if ~( nonZeroNeighbor == 0 || nonZeroNeighbor == 1 ...
||nonZeroNeighbor == 7 || nonZeroNeighbor == 8 ...
||transitSequence >= 2)
markMatrix(y,x) = 1;
fprintf(1, '(%d,%d) nonzero: %d transit: %d\n', ...
y,x, nonZeroNeighbor, transitSequence);
end
end
end
end
%Mask out all pixels found to be deleted
frame2(markMatrix > 0) = 0;
%Check if anything has changed
if sum(markMatrix(:)) > 0;changed = 1;end
end
%Final visualization
figure();imagesc(frame2);colormap(gray)

Resources