Issue with assigning output from a function in MATLAB - matlab

I am having problem when I try to store rmabackadj function's output to a variable. The function works properly when no output variable is assigned. This function is part of bioinformatics toolbox.
So the issue is when I try to run the following it works properly:
rmabackadj(myprobeData.PMIntensities)
But when I try to run the following I get an error:
>> A = rmabackadj(myprobeData.PMIntensities)
Warning: Colon operands must be real scalars.
> In rmabackadj>findMaxDensity at 255
In rmabackadj at 164
Error using ksdensity>parse_args (line 162)
X must be a non-empty vector.
Error in ksdensity (line 114)
[axarg,yData,n,ymin,ymax,xispecified,xi,u,m,kernelname,...
Error in rmabackadj>findMaxDensity (line 255)
[f, x] = ksdensity(z, min(z):(max(z)-min(z))/npoints:max(z), 'kernel', 'epanechnikov');
Error in rmabackadj (line 164)
mu = findMaxDensity( o(o < mu));
I searched for it online as well, but I couldn't find any result. Does anybody have any idea about the cause of this error?
PS: When I assign ans variable to a new variable, it is properly assigned.
A = ans

I'm pretty sure this is a bug.
Firstly, the reason it errors only when you supply an output argument is because there's an internal switch in the function that calculates different things based on nargout. That's an odd design, but not necessarily a bug.
Internal to rmabackadj there are two subfunctions findMaxDensity and findMaxDensity2. The main routine calls findMaxDensity, which is supposed to find an initial guess for the parameter mu. However (when I run the documentation example that you mention in your comment), it finds a terrible guess right on the edge, leading to an error.
When I edit the file to call findMaxDensity2 rather than findMaxDensity, it seems to produce a reasonable guess, and runs fine with no error. I can't vouch for whether the guess is actually "correct", but it seems reasonable to me, and it's only functioning as an initial guess to start off a better estimation process. (NB if you do this yourself, make sure to save a copy of the old version first).
I would guess that this is a bug, either that findMaxdensity is generating an unusually poor guess that should be caught, or that really it should be calling findMaxDensity2 and the code has not been updated to call a new subfunction.
Either way, I would report it to MathWorks.
PS I am running MATLAB R2011b. Check first if the issue has been fixed, or behaves differently, in more recent versions.

Mathworks confirmed this bug and issued a work around for it and mentioned this may be fixed in future releases.
One possible workaround is to add the following conditional at line 163 of rmabackadj function
% estimate mu from left-of-the-mode data
if any(o < mu)
mu = findMaxDensity( o(o < mu));
end
The bug for N<1000 samples has been confirmed as well but no work around has been issued yet.
I will update the thread if the work around for N<1000 samples bug.

Related

"Too Many Input Arguments" [duplicate]

This question already exists:
Error using symengine>#()0.0 Too many input arguments
Closed 3 years ago.
Exact error is:
Error using symengine>#()0.0
Too many input arguments.
Error in bdipuniodefun (line 18)
bdip = [s(4); s(5); s(6); (q/m_e)*(Ex(s(1),s(2),s(3)) + s(5)*Bz(s(1),s(2),s(3)) - s(6)*By(s(1),s(2),s(3))); (q/m_e)*(Ey(s(1),s(2),s(3)) +
s(6)*Bx(s(1),s(2),s(3)) - s(4)*Bz(s(1),s(2),s(3))); (q/m_e)*(Ez(s(1),s(2),s(3)) + s(4)*By(s(1),s(2),s(3)) - s(5)*Bx(s(1),s(2),s(3)))];
Error in odearguments (line 90)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode15s (line 150)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
Error in collisions6 (line 219)
[T,S] = ode15s(#bdipuniodefun, tspan, icv);
So we know where the error occurs, but I have been unable to resolve it nonetheless. This is an error that has also been inconsistent too. It does not always appear when I run the main script "collisions.m" but happens only when certain things get altered. Some examples: I start with too many electrons/particles, usually 1000+. Or I try to input a non-zero electric field. The electric field function is still being referenced but it is zero (Here comes the strange part). The reason I did this is because although the error goes away, the ode solver does not compute even close to the correct solutions I am looking for. I know for a fact that the results are wrong due to my knowledge of physics. However, when it does this, it does not give an error.
A Matlab staff member suggested that it may have something to due with my persistent variable definition but that is the only possible lead I have.
Troubleshooting methods I have already been through:
First if you look at the documentation from Matlab, it shows a specific syntax example to define the set of ODEs. In Matlab's syntax, they define each equation individually and then the vector of equations using the definitions. When I tried this syntax, the solver either did not solve the equations correctly, or it gave me the "too many input arguments" error. The way I made it run at all was to define every equation outright on a single line in "bdipodefun.m". Only that syntax worked and there is no good reason in my mind why this is the case because the definition that is used in one of the input arguments for the solver is the same. Using the Matlab recommended syntax even in simpler code, makes the ode solution incorrect.
I tried all ode solvers Matlab has to offer. The same issues persist or it cannot solve the equations at all.
I tried re-coding the entire simulation from scratch. I have found that this error still occurs even in more simpler codes.
Equation solver will also not solve the system correctly if there is no E-field. I found that if I create an E-field function and even just define it as zero within the file, the system solves correctly. It absolutely makes no sense as to why this is occurring.
Here is a description of what each file does in the code:
"collisionsmain.m" = Main script that references other files
"B_test.m" = B field function file referenced by collisionsmain
"E_test.m" = E field function file referenced by collisionsmain
"engen.m" = Generates energies for electrons based on a Maxwellian probability distribution curve
"maxdis.m" = Maxwellian distribution function used by engen
"engen.m" = Generates energies for electrons based on a Maxwellian
"posgen.m" = Generates a random, initial position on a sphere "bdipodefun.m" = ODE function set referenced by ODE solver in collisionsmain
Link to files: https://drive.google.com/drive/folders/19eJrgWYL4LQFwTY-VwguCCkta-pimZlL?usp=sharing
I didn't understand the code because it is complicated and big. Anyway, I tracked the error and find the source of the issue. The error comes from the number of parameters that have been sent to Ex, Ey, Ez in bdipuniodefun.m function. Ex, Ey, Ez functions receives 3 parameters while they can handle one parameter only.
The following code didn't send error and it shows the results.
bdip_r1 = [s(4); s(5); s(6)];
bdip_r2 = (q/m_e) * (Ex(s(1)) + s(5)*Bz(s(1),s(2),s(3))- s(6)*By(s(1),s(2),s(3)));
bdip_r3 = (q/m_e)*(Ey(s(1)) + s(6)*Bx(s(1),s(2),s(3)) - s(4)*Bz(s(1),s(2),s(3)));
bdip_r4 = (q/m_e)*(Ez(s(1)) + s(4)*By(s(1),s(2),s(3)) - s(5)*Bx(s(1),s(2),s(3)));
bdip =[bdip_r1;bdip_r2;bdip_r3;bdip_r4];

MATLAB: using a minimum function within symsum

I am trying to run code similar to the following, I replaced the function I had with one much smaller, to provide a minimum working example:
clear
syms k m
n=2;
symsum(symsum(k*m,m,0,min(k,n-k)),k,0,n)
I receive the following error message:
"Error using sym/min (line 86)
Input arguments must be convertible to floating-point numbers."
I think this means that the min function cannot be used with symbolic arguments. However, I was hoping that MATLAB would be substituting in actual numbers through its iterations of k=0:n.
Is there a way to get this to work? Any help much appreciated. So far I the most relevant page I found was here, but I am somewhat hesitant as I find it difficult to understand what this function does.
EDIT following #horchler, I messed around putting it in various places to try and make it work, and this one did:
clear
syms k m
n=2;
symsum(symsum(k*m,m,0,feval(symengine, 'min', k,n-k)),k,0,n)
Because I do not really understand this feval function, I was curious to whether there was a better, perhaps more commonly-used solution. Although it is a different function, there are many pieces online advising against the eval function, for example. I thought perhaps this one may also carry issues.
I agree that Matlab should be able to solve this as you expect, even though the documentation is clear that it won't.
Why the issue occurs
The problem is due the inner symbolic summation, and the min function itself, being evaluated first:
symsum(k*m,m,0,min(k,n-k))
In this case, the input arguments to sym/min are not "convertible to floating-point numbers" as k is a symbolic variable. It is only after you wrap the above in another symbolic summation that k becomes clearly defined and could conceivably be reduced to numbers, but the inner expression has already generated an error so it's too late.
I think that it's a poor choice for sym/min to return an error. Rather, it should just return itself. This is what the sym/int function does when it can't evaluate an integral symbolically or numerically. MuPAD (see below) and Mathematica 10 also do something like this as well for their min functions.
About the workaround
This directly calls a MuPAD's min function. Calling MuPAD functions from Matlab is discussed in more detail in this article from The MathWorks.
If you like, you can wrap it in a function or an anonymous function to make calling it cleaner, e.g.:
symmin = #(x,y)feval(symengine,'min',x,y);
Then, you code would simply be:
syms k m
n = 2;
symsum(symsum(k*m,m,0,symmin(k,n-k)),k,0,n)
If you look at the code for sym/min in the Symbolic Math toolbox (type edit sym/min in your Command Window), you'll see that it's based on a different function: symobj::maxmin. I don't know why it doesn't just call MuPAD's min, other than performance reasons perhaps. You might consider filing a service request with The MathWorks to ask about this issue.

for loop range syntax

I spent a couple of hours debugging a problem that I would have thought would have been a syntax error.
a = zeros(3);
for i=1:1size(a,2) % note the missing colon between 1 and size(a,2)
i
end
The following only displays
ans = 3
1
Essentially, it seems Matlab/Octave parses the above as:
for i=1:1
size(a,2)
i
end
Note however that
i=1:1size(a,2)
produces a syntax error. Is there a good reason that Matlab/Octave has this for loop syntax? Is there something that it's supposed to make easier? Just curious if anyone else has any thoughts about it. Thanks.
It is indeed a bit of a surprise that Matlab's syntax allows this. I don't know why this is allowed. One reason might be to allow for-loops on one line:
>> for i=1:3 disp(i);end
1
2
3
But interestingly, removing the space is not allowed:
>> for i=1:3disp(i);end
for i=1:3disp(i);end
|
Error: Unexpected MATLAB operator.
This reason for this is probably that a number followed by d is another way of writing a floating point number (3d10 == 3e10), so the parser/tokenizer initially thinks you define a number, but then gets confused when it sees the i. Daniel's example with fprintf does work, since a number followed by an f is not a valid number, so the tokenizer understands that you started a new token.
I guess that many years ago (>30?), when they defined matlab's syntax, they did not foresee that this could introduce this kind of hard-to-spot problems. I guess matlab was originally written by engineers for engineers, and not by someone who knows how to design a general purpose programming language. Other languages like C or Python use punctuation to separate loop conditions from loop body, so there is no ambiguity. I don't know if it is still possible to correct Matlab's syntax, since it might break old code that relies on the current behavior.
At least, if you use a recent version of Matlab, the editor warns for various problems in your code. Paying attention to the small red dashes in the right hand border could have saved you a few hours of debugging time (but maybe you were using octave). I try to make it a habit to fix all the warnings it indicates. For your code, it shows the following:
Your code is equivalent to
a = zeros(3);
for i=1:1
size(a,2)
i
end
There are some places where everyone would use newline or white space, but the parser itself does not require.
A minimal loop:
for i=1:3fprintf('%d',i),end
but I recommend to use at least a comma seperated version, everything else is horrible to read:
for i=1:3,fprintf('%d',i),end

adftest function error in lagmatrix

Using the adftest function in MATLAB's econometrics toolbox, I'm receiving the following error:
>> [h1,pVal1] = adftest(y1,'model','ARD')
Error using lagmatrix (line 25)
lagmatrix: wrong # of input arguments
Error in adftest>runReg (line 705)
yLags = lagmatrix(y,0:(testLags+1));
Error in adftest (line 417)
testReg = runReg(i,y,testT,testLags,testModel,needRegOut);
y1 is a <41x1> vector of doubles.
Has anyone received this error or have any thoughts on what the issue is? I am using this code right out of the box so I'm not sure what is going on. I'd post to MATLAB's site, but it is down for maintenance.
This is either a bug in Matlab, in which case you should submit it on the Matlab support site. Before you do that, you should check that you don't have a function lagmatrix on your path that shadows the built-in function. Type
which lagmatrix
on the command line. If the path does not point to your Matlab installation, you should move lagmatrix off the Matlab search path.
Also note that y1 should not contain all NaN, or be otherwise degenerate, so you may want to check the function using the sample data as suggested in the help to be sure it's a bug and not just your data.
I had the same problem with this function. In my case, the problem was the function lagmatrix (older version) in my MATLAB path and the adftest function was the newest version. The soluction was delete the older version of lagmatrix.

keving murphy's hmm matlab toolbox assertion error

I am working on a project that needs to use hidden markov models. I downloaded Kevin Murphy's toolbox. I have some problems about the usage. In the toolbox webpage, he says that first input of dhmm_em and dhmm_logprob are symbol sequence data. On their examples, they give row vectors as data. So, when I give my symbol sequence as row vector, I get error;
??? Error using ==> assert at 9
assertion violated:
Error in ==> fwdback at 105
assert(approxeq(sum(alpha(:,t)),1))
Error in ==> dhmm_logprob at 17
[alpha, beta, gamma, ll] = fwdback(prior,
transmat, obslik, 'fwd_only', 1);
Error in ==> mainCourseProject at 110
loglik(train_act) =
dhmm_logprob(orderedSymbols,
hmm{train_act}.prior,
hmm{train_act}.trans,
hmm{act}.emiss);
However, before giving this error, code works for some symbol vectors. When I give my data as column vector, functions work fine, no errors. So why exactly am I getting this error?
You might say that I should be giving not single vectors, but vector sets, I also tried to collect my feature vectors in a struct and give row vectors as such, but nothing changed, I still get assertion error.
By the way, my symbol sequence does not have any zeros, I am doing everything almost the same as they showed in their examples, so I would be greatful if anyone could help me please.
Im not sure, but from the function call stack shown above, shouldn't the last line be hmm{train_act}.emiss instead of hmm{act}.emiss.
In other words when you computing the log-probability of a sequence, you should pass components that belong to the same HMM model (transition matrix, emission matrix, and prior probabilities).
By the way, the ASSERT in the code is a sanity check that a vector of probabilities should sum to 1. Oftentimes, when working with very small values (log-probabilities), numerical stability issues can creep in... You could edit the APPROXEQ function to relax the comparison a bit, by giving it a bigger margin of error
This error message and the code it refers to are human-readable. An assertion is a guard put in by the programmer, to ensure that certain conditions are met. In this case, what is the condition? approxeq(sum(alpha(:,t)),1) I'd venture to say that approxeq wants the values to be approximately equal, so this boils down to: sum(alpha(:,t)) ~= 1
Without knowing anything about the code, I'd also guess that these refer to probabilities. The probabilities of a node's edges must sum to one. Hopefully this starts you down a productive debugging path. If you can't figure out what's wrong with your input that produces this condition, start wading into the code a bit to see where this alpha vector comes from, and how it ended up invalid.