Reputation: 994
I am trying to graph this custom function, but I can't find how. Is it even possible? All examples are about known functions (like sin or exp(x)).
I get the following error:
error: myfun: A(I,J,...) = X: dimensions mismatch
error: called from
myfun at line 28 column 16
grafica1 at line 54 column 2
>>
Code:
function ph = myfun(gamma)
...
for i = 1:N
....
A(i,i) = alfa*gamma+(gamma+1)*i+p*(N-i);
elseif j == i-1
A(i,j) = -i*(i-1);
elseif j == i+1
A(i,j) = -p*(N-i)*(i-1)*(i+1)/i;
...
b(i) = gamma * i;
end
v = A\b;
for i = 1:N
ph = ph + nchoosek(N,i)*p^i*v(i)/((1+p)^N);
end
endfunction
call:
y=myfun(gamma);
plot(gamma,y)
Upvotes: 0
Views: 62
Reputation: 943
The problem with your function is that it not designed with vectorization in mind. Specifically, when the input gamma
is a row vector, alfa*gamma+(gamma+1)*i+p*(N-i);
must also be a vector. Of course it will fail if you assign its value to A(i, j)
, which is a scalar.
I think your best option at this point is to compute the y values one at a time. This requires the least amount of change to your existing codebase.
y = zeros(size(gamma))
for i = 1:length(gamma)
y(i) = myfun(gamma(i));
end
plot(gamma, y);
Upvotes: 1