Clear Filters
Clear Filters

Matlab code errors with histogram generation code

6 views (last 30 days)
This is the coding that I have so far of my code. There aren't any errors with Part A1, and Part A2. I'm only starting to get an error at Part A3 with the histogram line. Most of this code in part 3 is provided by the professor as well.
"Part A: Simulating Probability Distributions"
"Part A1: Write a program that simulates the random varaible Y."
n = 1000
u = rand (1,n)
f_inv = @(x) log(2*(u-2))
X = f_inv(u)
"Part A2: Generate 100,000 random numbers from the distribution of Y"
n= 100,000
u = rand (1,n)
f_inv = @(x) log(2*(u-2))
X = f_inv(u)
"Part A3: Plot the density function"
a = 0;
b = 2.5;
m = 10;
histogram(X,m,"BinLimits",[a b],"Normalization","pdf","FaceColor",[.4 .4 .8])
hold on
f= @(x) (x>0).*log(2*(u-2))
t = linspace (a,b)
plot (t,f(t), "Color",[.2 .2 .6], "LineWidth",3)
The exact code that the professor provided in the handout is below this line of text. All I've done is change the equation in the line f = @(x) to log(2*u-2).
a = 0;
b = 2.5;
m = 10
histogram(X,m,’BinLimits’,[a b], ... ’Normalization’,’pdf’,’FaceColor’,[.4 .4 .8])
hold on
f = @(x) (x>=0).*(k/lambda).*(x/lambda).^(k-1).*exp(-(x/lambda).^k);
t = linspace(a,b); plot(t,f(t),’Color’,[.2 .2 .6],’LineWidth’,3)
These are the three errors that keep coming up no matter what itterations of the code I try.
  1. Error using histogram: Expected input number 1, x, to be real.
  2. Error in histogram>parseinput (line 263): validateattributes(x,{'numeric','logical','datetime','duration','categorical'},...
  3. Error in histogram (line 145): [opts,passthrough,dispatchToCategorical] = parseinput(args,firstaxesinput);
  3 Comments
Tomas
Tomas on 2 May 2023
How would I get rid of it? Assuming that my algebra with rearranging natural logs is correct. With the original equation after finding the inverse being -1*log(2-2u)=x.
Rik
Rik on 2 May 2023
If you intended to make f_inv depend on the input argument, you need this edit:
f_inv = @(x) log(2*(x-2));
X = f_inv(linspace(0,1,5))
X =
1.3863 + 3.1416i 1.2528 + 3.1416i 1.0986 + 3.1416i 0.9163 + 3.1416i 0.6931 + 3.1416i
As you can see, all values have an imaginary component. You can remove it easily, but it sounds like you should rethink your code instead of blindly removing the component you don't want to have.

Sign in to comment.

Answers (1)

VBBV
VBBV on 2 May 2023
Moved: Image Analyst on 2 May 2023
Use real function for f_inv
X = real(f_inv(u))

Community Treasure Hunt

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

Start Hunting!