How to rewrite this Matlab 2014 code with axis-subplots to 2016? - matlab

Code which I wrote for Matlab 2014 but which I want to rewrite it to Matlab 2016 such that it becomes more compact, since it is extranous now
hFig3=figure('Units', 'inches');
hax3_b1=axes('Parent', hFig3);
hax3_b2=axes('Parent', hFig3);
hax3_b3=axes('Parent', hFig3);
hax3_b4=axes('Parent', hFig3);
b1=subplot(2,2,1, hax3_b1);
b2=subplot(2,2,2, hax3_b2);
b3=subplot(2,2,3, hax3_b3);
b4=subplot(2,2,4, hax3_b4);
% Example of common expression
set([b1 b2], 'Units', 'inches'); % http://stackoverflow.com/a/39817473/54964
u=0:0.1:1; y=sin(u); C = [0 2 4 6; 8 10 12 14; 16 18 20 22];
imagesc(b1, u, y, C);
hold on;
plot(b2, u');
histogram(b3, u');
histogram(b4, u);
hold off;
drawnow;
Output is ok
OS: Debian 8.5 64 bit
MATLAB: 2014 but want to convert to 2016

You can simply write:
figure('Units','inches');
b1 = subplot(2,2,1);
b2 = subplot(2,2,2);
b3 = subplot(2,2,3);
b4 = subplot(2,2,4);
or preferably, if you want to have an array of the axes:
figure('Units','inches');
b(1) = subplot(2,2,1);
b(2) = subplot(2,2,2);
b(3) = subplot(2,2,3);
b(4) = subplot(2,2,4);
or use a simple for loop:
figure('Units','inches');
b(1:4) = axes;
for k = 1:numel(b)
b(k) = subplot(2,2,k);
end
In any option you choose there is no need for all the axes commands.
Here is all your 'demo' code:
b(1:4) = axes;
for k = 1:numel(b)
b(k) = subplot(2,2,k);
end
set(b(1:2), 'Units', 'inches');
u=0:0.1:1; y=sin(u); C = [0 2 4 6; 8 10 12 14; 16 18 20 22];
imagesc(b(1), u, y, C);
plot(b(2), u');
histogram(b(3), u');
histogram(b(4), u);
There might be no real need also in the figure command, it depends on what do with it.

If you're just looking for shorter you can eliminate most of the stuff at the beginning. You don't need the figure but I keep it as a matter of habit.
fh = figure;
x = 1:4;
b = arrayfun(#(y) subplot(2,2,y), x, 'UniformOutput',0);
b{1}.Units = 'inches';
b{2}.Units = 'inches';
u=0:0.1:1; y=sin(u); C = [0 2 4 6; 8 10 12 14; 16 18 20 22];
imagesc(b{1}, u, y, C);
plot(b{2}, u');
histogram(b{3}, u');
histogram(b{4}, u);

Related

Flip array data values - Matlab

How can I flip the array data values (based on Y values) so when I am plotting it will be like a mirror plot? (instead of looking like a “mountain” it will look like a “valley”)
Code:
clc
clear
close all
y = [4 5 6 9 10 20 22 25 22 20 15 10 0];
x = 0:12;
data = rot90(cat(1, x, y));
flipData = flip(data);
figure('Name','Data','NumberTitle','off');
plot(data(:,1),data(:,2),'r','LineWidth',2);
figure('Name','Flip Data','NumberTitle','off');
plot(flipData(:,1),flipData(:,2),'r','LineWidth',2);
You can plot max(y) - y:
y2 = max(y) - y;
plot(x, y2, 'r', 'LineWidth', 2);
You can reverse the direction of the axis, so that your graph is upside down, but Y-values are still correct.
y = [4 5 6 9 10 20 22 25 22 20 15 10 0];
x = 0:12;
data = rot90(cat(1, x, y));
figure('Name','Data','NumberTitle','off');
plot(data(:,1),data(:,2),'r','LineWidth',2);
figure('Name','max(y) - y','NumberTitle','off');
y2 = max(y) - y;
plot(x, y2, 'r', 'LineWidth', 2);
figure('Name','ax.YDir reverse','NumberTitle','off');
plot(data(:,1),data(:,2),'r','LineWidth',2);
ax = gca;
ax.YDir = 'reverse';

Curve fitting for non-linear data

I am trying to fit some data using lsqcurvefit in MATLAB but I am fairly new to this area.
xdata1 = [0 60 660 1250];
ydata1 = [0 18 23 31];
In the image below, the red line is the fit I want to achieve.
How can I achieve this fit?
How about polyfit() ?
Code here:
close all % be careful with following two lines
clear all
x = [0 60 660 1250];
y = [0 18 23 31];
p = polyfit(x,y,3);
xx = linspace(x(1), x(end), 100);
yy = polyval(p,xx);
plot(x,y,'o'); hold on; plot(xx,yy)

Radar plot Area Fill - Matlab

This is a radar plot script for MATLAB I copied from Google Search. I was hoping to use radar plot with different scales with 4 or 5 axes.
How would I fill the graph of this radar plot? Should I use patch or fill? I know this shouldn't take a long time to do this. My math isn't that great.
Thanks in advance,
Gary
function [f, ca, o] = spider(data,tle,rng,lbl,leg,f)
% create a spider plot for ranking the data
% function [f, ca, o] = spider(data,tle,rng,lbl,leg,f)
%
% inputs 6 - 5 optional
% data input data (NxM) (# axes (M) x # data sets (N)) class real
% tle spider plot title class char
% rng peak range of the data (Mx1 or Mx2) class real
% lbl cell vector axes names (Mxq) in [name unit] pairs class cell
% leg data set legend identification (1xN) class cell
% f figure handle or plot handle class real
%
% outptus 3 - 3 optional
% f figure handle class integer
% x axes handle class real
% o series object handles class real
%
% michael arant - jan 30, 2008
%
% to skip any parameter, enter null []
%
% examples
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27]','test plot');
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot', ...
% [[0:3:24]' [5:3:29]'],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'});
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot', ...
% [],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'});
%
% figure; clf; set(gcf,'color','w'); s = zeros(1,4);
% for ii = 1:4; s(ii) = subplot(2,2,ii); end
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27]','test plot 1',[],[],[],s(1));
%
% spider([1 2 3; 4 5 6; 7 8 9; 10 11 12; 13 14 15;16 17 18; ...
% 19 20 21; 22 23 24; 25 26 27],'test plot 2',[0 30],[],[],s(2));
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28]','test plot 3', ...
% [0 30],{'Label 1' 'Unit 1'; 'Label 2' 'Unit 2'; 'Label 3' 'Unit 3'; ...
% 'Label 4' 'Unit 4'},{'Case 1' 'Case 2' 'Case 3' 'Case 4' 'Case 5' ...
% 'Case 6' 'Case 7' 'Case 8' 'Case 9'},s(3));
%
% spider([1 2 3 4; 4 5 6 7; 7 8 9 10; 10 11 12 13; 13 14 15 16; ...
% 16 17 18 19; 19 20 21 22; 22 23 24 25; 25 26 27 28],'test plot 4', ...
% [[0:3:24]' [5:3:29]'],[],{'Case 1' 'Case 2' 'Case 3' 'Case 4'},s(4));
% data check
if nargin < 1; help spider; error('Need data to plot'); end
% size segments and number of cases
[r c] = size(data);
% exit for too few axes
if r < 3
errordlg('Must have at least three measuremnt axes')
error('Program Termination: Must have a minimum of three axes')
end
% title
if ~exist('tle','var') || isempty(tle) || ~ischar(tle)
tle = 'Spider Plot';
end
% check for maximum range
if ~exist('rng','var') || isempty(rng) || ~isreal(rng)
% no range given or range is in improper format
% define new range
rng = [min([min(data,[],2) zeros(r,1)],[],2) max(data,[],2)];
% check for negative minimum values
if ~isempty(ismember(-1,sign(data)))
% negative value found - adjust minimum range
for ii = 1:r
% negative range for axis ii - set new minimum
if min(data(ii,:)) < 0
rng(ii,1) = min(data(ii,:)) - ...
0.25 * (max(data(ii,:)) - min(data(ii,:)));
end
end
end
elseif size(rng,1) ~= r
if size(rng,1) == 1
% assume that all axes have commom scale
rng = ones(r,1) * rng;
else
% insuffent range definition
uiwait(msgbox(char('Range size must be Mx1 - number of axes x 1', ...
sprintf('%g axis ranges defined, %g axes exist',size(rng,1),r))))
error(sprintf('%g axis ranges defined, %g axes exist',size(rng,1),r))
end
elseif size(rng,2) == 1
% assume range is a maximum range - define minimum
rng = sort([min([zeros(r,1) min(data,[],2) - ...
0.25 * (max(data,[],2) - min(data,[],2))],[],2) rng],2);
end
% check for axis labels
if ~exist('lbl','var') || isempty(lbl)
% no labels given - define a default lable
lbl = cell(r,1); for ii = 1:r; lbl(ii) = cellstr(sprintf('Axis %g',ii)); end
elseif size(lbl,1) ~= r
if size(lbl,2) == r
lbl = lbl';
else
uiwait(msgbox(char('Axis labels must be Mx1 - number of axes x 1', ...
sprintf('%g axis labels defined, %g axes exist',size(lbl,1),r))))
error(sprintf('%g axis labels defined, %g axes exist',size(lbl,1),r))
end
elseif ischar(lbl)
% check for charater labels
lbl = cellstr(lbl);
end
if ~exist('leg','var') || isempty(leg)
% no data legend - define default legend
leg = cell(1,c); for ii = 1:c; leg(ii) = cellstr(sprintf('Set %g',ii)); end
elseif numel(leg) ~= c
uiwait(msgbox(char('Data set label must be 1XN - 1 x number of sets', ...
sprintf('%g data sets labeled, %g exist',numel(leg),c))))
error(sprintf('%g data sets labeled, %g exist',numel(leg),c))
end
% check for figure or axes
if ~exist('f','var')
% no figure or axes requested - generate new ones
f = figure; ca = gca(f); cla(ca); hold on; set(f,'color','w')
elseif ismember(f,get(0,'children')')
% existing figure - clear and set up
ca = gca(f); hold on;
elseif isint(f)
% generating a new figure
figure(f); ca = gca(f); cla(ca); hold on
else
% may be an axes - may be garbage
try
%is this an axes?
if ismember(get(f,'parent'),get(0,'children')')
% existing figure axes - use
ca = f; f = get(f,'parent'); hold on
end
catch
% make new figure and axes
disp(sprintf('Invalid axes handle %g passed. Generating new figure',f))
f = figure; ca = gca(f); cla(ca); hold on
end
end
% set the axes to the current text axes
axes(ca)
% set to add plot
set(ca,'nextplot','add');
% clear figure and set limits
set(ca,'visible','off'); set(f,'color','w')
set(ca,'xlim',[-1.25 1.25],'ylim',[-1.25 1.25]); axis(ca,'equal','manual')
% title
text(0,1.3,tle,'horizontalalignment','center','fontweight','bold');
% define data case colors
col = color_index(c);
% scale by range
angw = linspace(0,2*pi,r+1)';
mag = (data - rng(:,1) * ones(1,c)) ./ (diff(rng,[],2) * ones(1,c));
% scale trimming
mag(mag < 0) = 0; mag(mag > 1) = 1;
% wrap data (close the last axis to the first)
ang = angw(1:end-1); angwv = angw * ones(1,c); magw = [mag; mag(1,:)];
% make the plot
% define the axis locations
start = [zeros(1,r); cos(ang')]; stop = [zeros(1,r); sin(ang')];
% plot the axes
plot(ca,start,stop,'color','k','linestyle','-'); axis equal
% plot axes markers
inc = 0.25:.25:1; mk = .025 * ones(1,4); tx = 4 * mk; tl = 0:.25:1;
% loop each axis ang plot the line markers and labels
% add axes
for ii = 1:r
% plot tick marks
tm = plot(ca,[[cos(ang(ii)) * inc + sin(ang(ii)) * mk]; ...
[cos(ang(ii)) * inc - sin(ang(ii)) * mk]], ...
[[sin(ang(ii)) * inc - cos(ang(ii)) * mk] ;
[sin(ang(ii)) * inc + cos(ang(ii)) * mk]],'color','k');
% label the tick marks
for jj = 1:4
% temp = text([cos(ang(ii)) * inc(jj) + sin(ang(ii)) * tx(jj)], ...
% [sin(ang(ii)) * inc(jj) - cos(ang(ii)) * tx(jj)], ...
% num2str(chop(rng(ii,1) + inc(jj)*diff(rng(ii,:)),2)), ...
% 'fontsize',8);
temp = text([cos(ang(ii)) * inc(jj) + sin(ang(ii)) * tx(jj)], ...
[sin(ang(ii)) * inc(jj) - cos(ang(ii)) * tx(jj)], ...
num2str(rd(rng(ii,1) + inc(jj)*diff(rng(ii,:)),-2)), ...
'fontsize',8);
% flip the text alignment for lower axes
if ang(ii) >= pi
set(temp,'HorizontalAlignment','right')
end
end
% label each axis
temp = text([cos(ang(ii)) * 1.1 + sin(ang(ii)) * 0], ...
[sin(ang(ii)) * 1.1 - cos(ang(ii)) * 0], ...
char(lbl(ii,:)));
% flip the text alignment for right side axes
if ang(ii) > pi/2 && ang(ii) < 3*pi/2
set(temp,'HorizontalAlignment','right')
end
end
% plot the data
o = polar(ca,angw*ones(1,c),magw);
% set color of the lines
for ii = 1:c; set(o(ii),'color',col(ii,:),'linewidth',1.5); end
% apply the legend
temp = legend(o,leg,'location','best');
return
function [v] = rd(v,dec)
% quick round function (to specified decimal)
% function [v] = rd(v,dec)
%
% inputs 2 - 1 optional
% v number to round class real
% dec decimal loaction class integer
%
% outputs 1
% v result class real
%
% positive dec shifts rounding location to the right (larger number)
% negative dec shifts rounding location to the left (smaller number)
%
% michael arant
% Michelin Maericas Research and Development Corp
if nargin < 1; help rd; error('I/O error'); end
if nargin == 1; dec = 0; end
v = v / 10^dec;
v = round(v);
v = v * 10^dec;
function [val] = color_index(len)
% get unique colors for each item to plot
% function [val] = color_index(len)
%
% inputs 1
% len number of objects class integer
%
% outputs 1
% val color vector class real
%
% michael arant
if nargin < 1 || nargout < 1; help color_index; error('I / O error'); end
if len == 1
val = [0 0 0];
else
% initial color posibilities (no white)
% default color scale
col = [ 0 0 0
0 0 1
0 1 1
0 1 0
1 1 0
1 0 1
1 0 0];
% reduce if fewer than 6 items are needed (no interpolation needed)
switch len
case 1, col([2 3 4 5 6 7],:) = [];
case 2, col([2 3 4 5 6],:) = [];
case 3, col([3 4 5 6],:) = [];
case 4, col([3 5 6],:) = [];
case 5, col([5 6],:) = [];
case 6, col(6,:) = [];
end
% number of requested colors
val = zeros(len,3); val(:,3) = linspace(0,1,len)';
% interpolate to fill in colors
val(:,1) = interp1q(linspace(0,1,size(col,1))',col(:,1),val(:,3));
val(:,2) = interp1q(linspace(0,1,size(col,1))',col(:,2),val(:,3));
val(:,3) = interp1q(linspace(0,1,size(col,1))',col(:,3),val(:,3));
end
function [res] = isint(val)
% determines if value is an integer
% function [res] = isint(val)
%
% inputs 1
% val value to be checked class real
%
% outputs 1
% res result (1 is integer, 0 is not) class integer
%
% michael arant may 15, 2004
if nargin < 1; help isint; error('I / O error'); end
% numeric?
if ~isnumeric(val); error('Must be numeric'); end
% check for real number
if isreal(val) & isnumeric(val)
% check for integer
if round(val) == val
res = 1;
else
res = 0;
end
else
res = 0;
end

Intersection of line and curve Matlab

Well another problem has pop up recently.
I have a set representing a curve and a line I drew with the line() function.
So far my code is :
clc, clear all, close all;
n = 800/1500;
I = [ 0 1.1 4 9.5 15.3 19.5 23.1 26 28.2 30.8 33.3 35.9];
E_up = [ 5.8 10.5 28 60.3 85.5 100.3 108 113.2 117 120.5 123.5 126];
E_up = E_up./n;
Iw = [ 34 31.5 28.2 23.9 19.9 16.1 13 8.1 3.5 1.2 0 NaN];
E_down = [124.6 122.5 118.8 112.2 103.9 93.1 81.6 59.1 29.6 14.5 9.5 NaN];
E_down = E_down./n;
x_est = I;
y_est = spline(Iw,E_down,x_est)
A(:,1)= E_up
A(:,2) = y_est
ma = mean(A,2)
% figure()
% hold all
% % plot(x_est,y_est,'ro')
% plot(I,E_up,'b-',Iw,E_down,'g-')
% plot(I,ma,'r')
% grid on
% legend('up','down','mean')
%dane_znamionowe
clc, clear all, close all;
%data_entry
n = 800/1500;
I = [ 0 1.1 4 9.5 15.3 19.5 23.1 26 28.2 30.8 33.3 35.9];
E_up = [ 5.8 10.5 28 60.3 85.5 100.3 108 113.2 117 120.5 123.5 126];
E_up = E_up./n; %rescalling_EMF
Iw = [ 34 31.5 28.2 23.9 19.9 16.1 13 8.1 3.5 1.2 0 NaN];
E_down = [124.6 122.5 118.8 112.2 103.9 93.1 81.6 59.1 29.6 14.5 9.5 NaN];
E_down = E_down./n; %rescalling_EMF
Un = 220;
In = 28.8;
wn = 1500;
wmax = 3000;
P = 5.5e3;
Rs = 15.8/25;
%interpolation
x_est = I;
y_est = spline(Iw,E_down,x_est);
%mean_values
A(:,1)= E_up;
A(:,2) = y_est;
ma = mean(A,2);
%party_Xd
figure()
[ax,h1,h2] = plotyy(I+30,wn,I,ma,'plot','plot');
set(ax(1),'ylim',[0 3000],'ytick',[1500 3000]);
set(ax(2),'ylim',[0 300],'ytick',[100 200 300]);
hold(ax(1))
hold(ax(2))
%stable_parts
set(ax,'NextPlot','add')
plot(ax(2),I,ma,'b')
plot(ax(2),0,Un,'m*')
i2 = 0:0.01:70;
plot(ax(2),i2,Un-(i2*Rs),'m--')
iin = 0:1:300;
plot(ax(2),In,iin,'g-')
plot(ax(1),i2,wn,'k-','linewidth',8)
plot(ax(1),28.8,1500,'g*')
%loop
p1x = [35 45 55 65];
for ii = 1 :length(p1x)
x11 = p1x(ii);
y11 = 0;
x21 = In;
y21 = wn;
x1 = [35 45 55 65];
y1 = [0 0 0 0];
x2 = [In In In In];
y2 = [wn wn wn wn];
slope = (y21-y11)/(x21-x11);
xLeft = 0;
yLeft = slope * (xLeft - x11) + y11;
xRight = 70;
yRight = slope * (xRight - x11) + y11;
plot(ax(2),x11,0,'r.')
a1 = line([xLeft, xRight], [yLeft, yRight], 'Color', 'c');
x0 = (max(min(x1),min(x2))+min(max(x1),max(x2)))/2;
fun1 = #(x) interp1(x1,y1,x,'linear');
fun2 = #(x) interp1(x2,y2,x,'linear');
difffun = #(x) fun1(x)-fun2(x);
crossing = fzero(difffun,x0); %crossing x coordinate
crossval = fun1(crossing);
end
My graph looks like this which is pretty decent.But I need to find the intersection point of the cyan line and blue curve.
An answer based on my solution to a similar question:
%dummy input
x1=[0 1 2 3];
y1=[1 4 2 0];
x2=[-1 3 4 5];
y2=[-1 2 5 3];
x0 = (max(min(x1),min(x2))+min(max(x1),max(x2)))/2;
fun1 = #(x) interp1(x1,y1,x,'linear','extrap');
fun2 = #(x) interp1(x2,y2,x,'linear','extrap');
difffun = #(x) fun1(x)-fun2(x);
crossing = fzero(difffun,x0); %crossing x coordinate
crossval = fun1(crossing); %substitute either function at crossing point
plot(x1,y1,'b-',x2,y2,'r-',crossing,crossval,'ks');
legend('line1','line2','crossover','location','nw');
after which your crossing point is given by [crossing, crossval].
Result:

Matlab - creating an automatically animation transition for a line

I have the following picture:
and I want to create a continuous transition. The blue line (-20deg-start) goes until become like (22deg - original), and then goes until become like (60deg-stop).
the code to generate this lines is:
>> clear all
>> x=[0 11 20 34];
>> y=[2 8 17 32];
>> z=[9 20 29 43];
>> v=[16 23 32 43];
>> w=[15 26 35 49];
>> t=[30 40 47 55];
>> figure
>> hold on
>> plot(t,x, t,y, t,z, t,v, t,w)
Is it possible with the help of Matlab?
Thanks!
The following example shows how to do a linear transition between two curves, provided they are both defined on the same set of x values.
x = linspace(0,1,200); %// x values
y1 = log(1+x); %// y values of line 1
y2 = 1-x.^2; %// y values of line 2
c1 = [1 0 0]; %// red
c2 = [0 0 1]; %// blue
plot(x, y1, ':', 'color', c1); %// plot first line
hold on
plot(x, y2, ':', 'color', c2); %// plot second line
tt = linspace(0,1,100); %// define time axis, between 0 and 1. Adjust "100" for smoothness
h = plot(x, y1, '-', 'color', c2); %// moving line. Initially coincides with line 1
for t = tt
y = y1*(1-t) + y2*t;
c = c1*(1-t) + c2*t;
set(h, 'YData', y, 'Color', c); %// update y values and color of moving line
pause(.02) %// adjust ".02" as needed
end
Yes you can (well from what I understand you wish to achieve). You can put all your data into 1 big array and loop through each row and display it, with a small pause between each set of data.
Example:
clear
clc
close all
clear all
x=[0 11 20 34];
y=[2 8 17 32];
z=[9 20 29 43];
v=[16 23 32 43];
w=[15 26 35 49];
t=[30 40 47 55];
%// Put everything in single array
AllArrays = [x;y;z;v;w];
figure
hold all
%// Loop through each rows
for k = 1:size(AllArrays,1)
plot(t,AllArrays(k,:))
%// Make a pause to see output
pause(.5)
end
Output:
Is this what you meant? Or maybe a smoother transition?