KroneckerDelta in matlab - matlab

This link shows that there is a kronecker delta function in matlab. However:
>> help kroneckerDelta
kroneckerDelta not found
I am using R2011b, so maybe this wasn't programmed into the toolkit yet?
EDIT:: It works in MuPad, just not in matlab...
.

The Kronecker delta returns 1 if j==k...
So you could simplify the expression with:
function d=kronDel(j,k)
d=j==k
end
Luckily, MATLAB represents booleans as (0,1)

I don't see it in my R2012b so perhaps not. Unless you need the symbolic math, you could always write your own. Something as simple as
function d = kronDel(j,k)
if j == k
d = 1;
else
d = 0;
end

You can also do this inline, like
( a == b )
However, using an anonymous function is a nice way to convert a one liner like this into something that is more readable
kronDel = #(j, k) j==k ;
kronDel( 2, 1 )
kronDel( 2, 2 )

Your link to is to the MuPAD function kroneckerDelta -note the URL and the funky typography of the examples. You won't see it in any version of Matlab because it's only available through MuPAD (type mupad in your command window and try in the window that launches). I have no idea when it was added to MuPAD, I know that it's at least in R2012b. You may have it even if the help command returns nothing.
If you have kroneckerDelta in R2011b, you won't be able to run it from the regular command window or Editor in the normal fashion.
evalin(symengine,'kroneckerDelta(1,1)')
or the more flexible
feval(symengine,'kroneckerDelta',1,1)
See more here. However, if you're not working with symbolic math, there's really no reason to use this function that I can see -it's not even vectorized! I'd go with a solution that fully emulates kroneckerDelta's behavior in double precision:
function d=kronDel(m,n)
if nargin == 1
d = double(m==0);
else
d = double(m==n);
end

Related

What's wrong this code in Matlab: numeric::solve(x^6 - PI*x^2 = sin(3), x)

I'm new to Matlab and I'm attempting to use it to solve equations numerically. I consulted the Matlab documentation, found the following code:
numeric::solve(x^6 - PI*x^2 = sin(3), x)
I tried to execute it, but Matlab says:
numeric::solve(x^6 - PI*x^2 = sin(3), x)
|
Error: Unexpected MATLAB operator.
I'm confused. Could you tell me what's wrong? I'm using Matlab R2013a on OS X Mavericks.
try using
syms x
sol_x = solve(x^6 - pi*x^2 == sin(3), x);
sol_x = sym2poly(sol_x);
You try to use a command that only works in the MuPAD Notebook Interface in MATLAB. The documentation got better over time pointing this out. Does 2013a include the vpasolve command? If yes, that is probably what you are looking for.
Perhaps you typed "solve" and "matlab" into Google and came across this page. Note the warning in the yellow box at the top of the page that #ChristopherCreutzig alluded to in his answer. MuPAD is a separate environment available to Matlab users – type mupad in your command window and you'll be able to run your command – but its functions are not directly callable from within Matlab. Many (if not most) of the functions in the Symbolic Math toolbox use the MuPAD engine under the hood. In your case you can call numeric::solve from within Matlab like this:
syms x;
s = feval(symengine, 'numeric::solve', x^6 - sym(pi)*x^2 == sin(3), x)
or using the older string format:
s = feval(symengine, 'numeric::solve', 'x^6 - pi*x^2 = sin(3)', 'x')
The output of either can then be converted to double precision column vector with s = double(s.'). However, in this case there seems to be no reason not to use sym/solve instead:
syms x
s = double(solve(x^6 - sym(pi)*x^2 == sin(3), x).');
See this for further details and other options for calling MuPAD functions from within Matlab.

Function to find entries with same maximum value in a vector

In my project I need a function which returns the index of the largest element of a given vector. Just like max. For more than one entry with the same maximum value (which occurs frequently) the function should choose one randomly. Unlike max.
The function is a subfunction in a MATLAB Function Block in Simulink. And the whole Simulink model is compiled.
My basic idea was:
function ind = findOpt(vector)
index_max = find(vector == max(vector));
random = randi([1,length(index_max)],1);
ind = index_max(random);
end
But I got problems with the comparison in find and with randi.
I found out about safe comparison here: Problem using the find function in MATLAB. Also I found a way to replace randi([1,imax],1): Implement 'randi' using 'rand' in MATLAB.
My Code now looks like this:
function ind = findOpt(vector)
tolerance = 0.00001;
index_max = find(abs(vector - max(vector)) < tolerance);
random = ceil(length(index_max)*rand(1));
ind = index_max(random);
end
Still doesn't work. I understand that the length of index_max is unclear and causes problems. But I can not think of any way to know it before. Any ideas how to solve this?
Also, I'm shocked that ceil doesn't work when the code gets executed?? In debug mode there is no change to the input visible.
I thought about creating an array like: index_max = abs(vector - max(vector)) < tolerance; But not sure how that could help. Also, it doesn't solve my problem with the random selection.
Hopefully somebody has more ideas or at least could give me some hints!
I am using MATLAB R2012b (32bit) on a Windows7-64bit PC, with the Lcc-win32 C 2.4.1 compiler.
Edit:
Vector usually is of size 5x1 and contains values between -2000 and zero which are of type double, e.g. vector = [-1000 -1200 -1000 -1100 -1550]'. But I think such a simple function should work with any kind of input vector.
The call of length(index_max) causes an system error in MATLAB and forces me to shut it down. I guess this is due to the strange return I get from find. For a vector with all the same values the return from find is something like [1.000 2.000 1.000 2.000 0.000]' which doesn't make any sense to me at all.
function v= findOpt(v)
if isempty(v)
return;
end
v = find((max(v) - v) < 0.00001);
v = v(ceil(rand(1)*end));
end
I was indeed overloading, just like user664303 suggested! Since I can not use objects in my project, I wanted an function that behaves similar, so I wrote:
function varargout = table(mode, varargin)
persistent table;
if isempty(table) && ~strcmp(mode,'writeTable')
error(...)
end
switch mode
case 'getValue'
...
case 'writeTable'
table = ...
...
end
end
Wanted to avoid passing the dimensions for the table in every call and thought it would be enough if the first call initializes the Table with mode='writeTable'. Looks like this caused my problem.
No problems after changing to:
if isempty(table)
table = zeros(dim1,dim2,...)
end

Matlab plot won't return correct results

I have written a function that is the beginning of a Poisson Process
function n_t = PoisProc2(t,tao,SIZE)
n_t=0;
for n=1:SIZE
if t>tao(1,n)
n_t=n_t+1;
end
end
end
tao is simply an array of random doubles of length SIZE. For simplicity we'll say [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,20]
So this functions purpose is to count how many elements of tao that t is greater than for any given t.
This code works fine when I simply write
PoisProc2(3,tao,20);
the answer I get is 19 as expected, but if I write
x=1:.01:20;
y=PoisProc2(x,tao,20);
plot(x,y,'-')
y shows up as 0 in the workspace (I would expect an array of length 1901) and my plot also reads 0. I'm pretty new to Matlab, but this seems like a pretty simply thing I'm trying to do and I must be missing something obvious. Please help!
Your code does not work as you are giving a vector. So your if condition is not working as you expect.
First initialize n_t with a vector :
n_t=zeros(1,length(t))
instead of
if t>tao(1,n)
n_t=n_t+1;
end
Vectorize your expression :
n_t = n_t + (t>tao(1,n))
Cheers
Because x is a vector in your last example, the "if t>tao(1,n)" statement in your function behave totally different from what you think.
This function below should give you the right result.
function ret = PoisProc2(thresholds, vec)
ret = zeros(size(thresholds));
for k = 1:numel(thresholds)
ret(k) = numel(nonzeros(vec > thresholds(k)));
end
Side comments:
Your original function is quite C/Java style. You can see in my function, it's replaced by a one-liner "numel(nonzeros(vec > thresholds(k)))", which is more MATLAB style.
I think this can be done with hist() function. But this probably is easier to understand.

ichol instead of chol in MATLAB 2013

I have a code that I used to run without any problem in MATLAB 2012.
But when I switched to MATLAB 2013 my code doesn't work anymore and I get the following error:
CHOLINC has been removed. Use ICHOL instead.
I'm using this line of code which is in cvx package and specifically in quad_form.m file:
[ R, p ] = chol( Q );
And so I'm wondering how can I replace chol by ichol.
First of all you should read the documentation, it can be found by typing help ichol or doc ichol. Here is a copy as well: http://www.mathworks.nl/help/matlab/ref/ichol.html
I am not 100% sure, but my first try would be to check whether changing chol to ichol will do the trick.
If the problem is that the function call is made in code that you cannot alter, then (after you figure out what the call should be) you can create your own chol function that calls ichol.
As #Dan suggested, matlab's chol is probably being "overridden" by a user- or toolbox-defined chol which internally calls cholinc (now ichol).
But more importantly, you should understand what is going on in your problem. Cholesky facotrizations (chol) only work if your matrix Q is Hermitian and positive-semidefinite.
Probably, somebody wrote their own chol which attempts a Cholesky factorization, and if it fails, does an incomplete Cholesky factorization (ichol / cholinc) instead.
You could just implement that yourself, e.g. assuming the matrix Q is real-valued:
%untested.
R = [];
p = [];
if Q==Q' && all(eig(Q) >= 0)
[R,p] = chol(Q);
else
[R,p] = ichol(Q);
end
addition
You may want to use try & catch instead of if & else, if you want to be completely sure that no hidden warnings/error messages cause your program to bail.
edit
Changed condition on Q to actually checking for positive semi-definiteness. Thanks for pointing that out #woodchips.

How do I properly setup numerical integration in MATLAB?

I'm looking to integrate this expression:
However I seem to be having problems setting up the function. As outlined in this MATLAB explanation, I've defined a separate function named 'NDfx.m' which looks like this:
function [ y ] = NDfx(x)
y = (1/sqrt(2*pi))*exp(-.5*x^2); % Error occurs here
end
However when I call it within my main function I get an error at the commented line above. My main function looks like this:
function[P] = NormalDistro(u,o2,x)
delta = x-u;
dev = abs((delta)/o2); % Normalizes the parameters entered into function
P_inner = quad(#NDfx,-dev,dev); % Integrates function NDfx from -dev to dev (error here)
P_outer = 1 - P_inner; % Calculation of outer bounds of the integral
if delta > 0
P = P_inner + (P_outer/2);
elseif delta < 0
P = P_outer/2;
elseif dev == 0
P = .5;
end
end
The specific error that I get is:
Error in ==> mpower
Inputs must be a scalar and a square matrix
You've setup everything correctly for integration. The error is in the definition of the function itself. When using variables for function that will be integrated, a "." (period) must precede operators like ^ and * when they are applied to the variable:
function [y] = NDfx(x)
y = (1/sqrt(2*pi))*exp(-.5*(x.^2));
end
Krono and user57368 are correct. They have already correctly answered your actual question. My answer is merely to answer the question you did not ask. That is, why are you using quad here at all? The point is that many people want to integrate a function of that form, and it has been done already! Use existing tools to solve your problems, as those tools will often have been written by someone who knows how to solve the problem accurately and efficiently.
In this case, the existing tool is comprised of the functions erf and erfc. They provide an accurate, efficient, vectorized solution to your problem. The only thing you will need to do is figure out how to transform those integrals to your current problem, done by a simple scaling of the input to erf and the output.