how do I create a function

I have the code below to plot the kernel distribution of the data x1, x2,x3 where those x-s are vectors. But instead of changing the code
each time I have new data I want to create a function that runs each time I call it on the new data.
Also if you could help me to use as x-axis the values of +/-std of each data set instead of inisiating with s=(-3:0.01:3);
x1=(x1-mean(x1))/std(x1);
x2=(x2-mean(x2))/std(x2);
x3=(x3-mean(x3))/mean(x3);
% Creating empirical distribution and plot the results together with normal
% distribution N(0,1)
pd1=fitdist(x1,'Kernel');
pd2=fitdist(x2,'Kernel');
pd3=fitdist(x3,'Kernel');
pd4=makedist('Normal');
s=(-3:0.01:3);
y1=(pdf(pd1,s))';
y2=(pdf(pd2,s))';
y3=(pdf(pd3,s))';
y4=(pdf(pd4,s);
figure
figure,plot(s,y1,'-b',s,y2,'k',s,y3,'-g',s,y4,'-r')

4 个评论

So you want to have code that allows you to input x4, x5, etc without having to edit the code?
function gjastas_function(x1, x2, x3)
Sorry Walter, can I ask how can I get the real values of x1, x2, and x3 in the x-axis not the normalized mean in order to compare where their mean's are positioned(figure attached)?
Can I call your function like this:
figure=gjastas_function(x1,x2,x3)

请先登录,再进行评论。

回答(1 个)

You can use something like this:
close all
x1=rand(10,1);
myfun(x1)
x2=rand(10,1);
myfun(x2)
x3=rand(10,1);
myfun(x3)
x4=rand(10,1);
myfun(x4)
function myfun(x)
%write documentation here
x=(x-mean(x))/std(x);
% Creating empirical distribution and plot the results together with normal
% distribution N(0,1)
pd=fitdist(x,'Kernel');
s=(-3:0.01:3);
y=pdf(pd,s);
h=get(gcf,'UserData');
if isempty(h)%initialize
h.C=get(gca,'colororder');
h.counter=0;
pd_=makedist('Normal');
y_=pdf(pd_,s);
plot(s,y_,'-k'),hold on
end
h.counter=h.counter+1;
if h.counter>size(h.C,1),h.counter=1;end
set(gcf,'UserData',h)
C=h.C(h.counter,:);
plot(s,y,'-','Color',C)
end

4 个评论

I have saved the function but I cannot call it. I got this error:
Error using matlab.ui.Figure/get
There is no UserData property on the Figure class.
Error in myfun (line 9)
h=get(gcf,'UserData ');
What release are you using?
Sorry, I am not sure, if I understood your question Rik but I would like to get a figure like the figure I have attached. So, to get the real values of x1, x2, and x3 in the x-axis not the normalized mean in order to compare where their mean's are positioned? I have also upploaded the data below.
What I meant was: which version of Matlab are you using? I'm using R202a and this code works. So if you are using the same release you must be running the code differently.
If you want to essentially plot the histograms, why not use the histogram function? And if you want to use the actual data, and not the normalized mean, you should probably remove lines like x1=(x1-mean(x1))/std(x1);.

请先登录,再进行评论。

标签

提问:

2020-6-9

评论:

Rik
2020-6-10

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by