Need help with this code..

3 views (last 30 days)
Sim
Sim on 15 Oct 2012
Hello everyone,
I am writing this function for plotting histograms. I need help with making this code very generic. That is it should work for any set of data. the code is as follows:
function us(x,bins,units,name)
[p q]=hist(x,bins);
barh(q,p)
xlabel(units)
ylabel(name)
yy_tick=[min(q) mean(q) median(q) max(q)];
yy_label={num2str(min(x)),strcat('mean = ',num2str(mean(x))) , strcat('median = ',num2str(median(x))),num2str(max(x))};
Ynew=sort(yy_tick);
for i=1:length(Ynew)
j=find(Ynew(1,i)==yy_tick);
y_label(1,i)=yy_label(1,j(1,1));
end
set(gca,'YTick',Ynew)
set(gca,'YTickLabel',y_label)
I need to understand how can I use a nargin function in this code so that if say nargin= 2 and if input is a scalar then it probably is (x,bins) and if it a text the tht would be units or name. Does this make sense? Please help me understand. I am very very new to matlab. Thanks much in advance.

Answers (1)

Star Strider
Star Strider on 15 Oct 2012
You are correct with respect to using nargin. For example:
if nargin < 2
fprintf(2,'\n\nError in function ''us'': Not enough input arguments.\n\n')
return
end
You can also check to be sure the arguments are the correct class. For example:
if ~isnumeric(x)
fprintf(2,'\n\nError in function ''us'': Argument ''x'' must be numeric.\n\n')
return
end
if ~ischar(units)
fprintf(2,'\n\nError in function ''us'': Argument ''units'' must be a string.\n\n')
end
and so on for the others if you want to check them.
  2 Comments
Sim
Sim on 15 Oct 2012
Thank you so much for you reply. Here nargin function prints what we ask it to print. But for eg if i say nargin==2 What i want to know is, is there a way to find out that the input given was (x,bins) and not (x,name) and I want the function to run for only those 2 inputs and then plot the hist accordingly?
Star Strider
Star Strider on 15 Oct 2012
If nargin = 2, the first two arguments will be the arguments nargin checks for. They will appear in your us function as x and bins respectively. If you want to be sure they are numeric, use the
if ~isnumeric(x)
...
end
and copy and adapt it to:
if ~isnumeric(bins)
...
end
If nargin == 2, that means the units and name arguments are not provided to your us function, and you need to set them to be empty strings. In that situation, the first lines in your function then need to be:
if nargin == 2
units = '';
name = '';
end
You can also test for units and name individually:
if nargin == 3 % Test for 'units'
name = ''; % Argument 'units' exists but not 'name'
end
That should test for everything, and your function should work with varying numbers of arguments. Be sure these all appear before any other statements in your function.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!