Matlab function doesnt run when called from AppDesigner

I have a problem in which if I call a function from Command Window it functions properly, but when I call it from App Designer it says there is a mistake in the matrix multiplication dimensions. I think this is very weird, because if there was a mistake related to a matrix shouldn't it show in both modes??? I've been using it from command line for a while and its been working fine, Im not sure why it doesnt run from AppDesigner.
This is the code :
function [resultCode, resultX1, resultX2, Z] = busquedas_function(Xo, Delta, Iter, Fun)
resultCode = 0;
% 1 = success
% 2 = failed
%input es un comando de solicitud de entrada de datos del usuario.
f=inline(Fun);
Yo=f(Xo);
if Yo==0
fprintf('\n\nSOLUCION:\n');
fprintf ('Xo es raiz\n\n');
else
X1=Xo+Delta;
Cont=1;
Y1=f(X1);
Z=[Cont,Xo,Yo,(Yo.*Y1)];
%Z es una matriz la cual permitira observar lo datos como una tabla a la
%finalizacion del programa
%La sentencia While ejecuta todas las órdenes mientras la expresión sea
%verdadera.
while (((Yo*Y1)>0) & (Cont<Iter ))
Xo=X1;
Yo=Y1;
X1=Xo+Delta;
Y1=f(X1);
Cont=Cont+1;
Z(Cont,1)=Cont;
Z(Cont,2)=Xo;
Z(Cont,3)=Yo;
Z(Cont,4)=Yo*Y1;
%las z son las posiciones asignadas en la tabla a los resultados que se
% observarán
end
if Y1==0
fprintf('\n\nSOLUCION:\n')
fprintf('%g es raiz\n\n',X1)
resultX1 = X1;
resultX2 = X1;
else
if Yo*Y1<0
fprintf('\n\nSOLUCION:\n')
fprintf ('El intervalo que contiene la raíz es[%g,%g]\n\n',Xo,X1)
resultCode = 1;
resultX1 = Xo;
resultX2 = X1;
else
fprintf('\n\nSOLUCION:\n')
fprintf ('Fracaso en %g iteraciones\n\n',Iter)
resultCode = 2;
resultX1 = 0;
resultX2 = 0;
end
end
end
fprintf('TABLA\n\nIteraciones Xo Yo Yo*Y1 \n\n');
disp(Z);
%La funcion disp permite visualizar la tabla, obtenida de los resultados de
%la secuencia while
ezplot(f);
%El comando ezplot permite grafica una función.
end
if I call it from command line it runs correctly
But calling it with same parameters from App Designer brings up this error:
"Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-11.
Error in busquedas_function (line 40)
Z(Cont,3)=Yo;"

5 Comments

The questions is which of the two matrices has the wrong size? The LHS or RHS?
Maybe you can check inside the code where the size of the matrices diverge? (command line versus appdesigner)
The one on the right has the wrong size, they both should be sized as 1-by-1.
Ill start printing the results on every step and compare both calls to see if maybe its a conversion mistake or something.
Why don't you start by calling it with the exact same values in app designer (-2, 0.5, 20, '3*x*x+5*x+2') and confirm that it's about your arguments and not the fact that it's being called from app designer?
My guess is you're passing in a character and you meant to pass in a number (e.g. '-2' instead of -2) and a str2num will resolve the issue.
I checked and by putting values on inside the App Designer code it does work (2nd commented line)
However I'm not sure why my Edit Fields are not passing the arguments as they should.
I double checked and Xo, Delta and Iter are numeric values as they should,Funcion is a text field, since I have funcion as a string I thought I needed to convert it to a char vector, so I tried converting it with:
Fun = app.FuncionEditField.Value
Func = convertStringsToChars(Fun) )
so Im a bit confused as to where is the bad casting.
I mean, it would seem like its the same data, at least to my clueless self.
Are you sure your editfield values are numbers and not characters that contain numbers? If I do:
h=uieditfield;
And then type the number 0.5 in there, and then do h.Value, I get '0.5' not 5. I think you want str2num (I previously wrote num2str by accident sorry!)
Xo = str2num(app.XoEditField.Value);
Delta = str2num(app.DeltaEditField.Value);
Iter = str2num(app.IteraEditField.Value);

Sign in to comment.

 Accepted Answer

You're passing in characters containing numbers the values instead of the values themselves. Use str2num to convert before calling your function.
Xo = str2num(app.XoEditField.Value);
Delta = str2num(app.DeltaEditField.Value);
Iter = str2num(app.IteraEditField.Value);
For a robust app you might want to also validate that they are values before calling the function. You could do this with by checking the result of calling str2num, or by introducing an arguments block (with the mustBeNumeric validator) into busquedas_function.

8 Comments

I am very grateful for the explanation, it has helped me understand all of matlab concepts a lot better!
The argument block seems super useful and I implemented it right away!! Thanks a lot, however, it has not seemed to fix my original issue, sadly, as of now my function looks like this:
function SubmitButtonPushed(app, event)
Xo = str2double(app.XoEditField.Value);
Delta = str2double(app.DeltaEditField.Value);
Iter = str2double(app.IteraEditField.Value);
Fun = convertStringsToChars(app.FuncionEditField.Value);
% [resultCode, resultX1, resultX2, Z] = busquedas_function(-5,0.5,20,'x*x*x+4*x*x-10')
[resultCode, resultX1, resultX2, Z] = busquedas_function(Xo,Delta,Iter,Fun);
app.Resultadox1EditField.Value = resultX1;
app.Resultadox2EditField.Value = resultX2;
app.SuccessEditField.Value = resultCode;
end
But the problem persists, same warning:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise multiplication, use '.*'.
Error in busquedas_function (line 42)
while (((Yo*Y1)>0) & (Cont<Iter ))
I already applied the arguments to my function like this:
function [resultCode, resultX1, resultX2, Z] = busquedas_function(Xo, Delta, Iter, Fun)
arguments
Xo double
Delta double
Iter double
Fun char
end
So Im again a bit confused as to why it seems to recognize some value as a matrix or similar?
I'm so sorry, I was sure that was the source of the problem! But I'm sure we can solve it.
To restate where we are...
We know it works when called as:
busquedas_function(-5,0.5,20,'x*x*x+4*x*x-10')
but not as
busquedas_function(Xo,Delta,Iter,Fun);
So it's clear that at least one of these values is different, right?
It seems like now might be a good time to learn about MATLAB breakpoints! If you click on the left side of the editor window, at the line where it fails (line 42), you should see a red box. When you run the code (click on the button) MATLAB will pause at that moment. Then you can examine Yo and Y1 (you can hover over the variables, or look in the Workspace area, or just type them in at the command prompt). Is one of them empty? is one of them not scalar? When your down you can click Quit Debugging at in the toolstrip.
This will likely give a strong hint as to what's going on.
In reality I'd probably actually just set my breakpoint in app designer, clicking on the left side of the app designer code view window just before busquedas_function is called, as we know that everything works okay here with hard coded values but not with the variables. You can even run code at this paused point, like Xo==-5 etc.
Here's more info on breakpoints which will show you what they should look like (though if memory serves me correctly they appear slightly different in the App Designer editor from the regular MATLAB editor) https://www.mathworks.com/help/matlab/matlab_prog/set-breakpoints.html
Side note - for the arguments block I probably would have done something like:
Xo (1,1) double {mustBeNumeric}
Because this guarantees that it's numeric, and scalar. But this is maybe something to tweak after the code is working!
I got this info while trying to use the breakpoints!
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise multiplication,
use '.*'.
Error in busquedas_function (line 42)
while (((Yo*Y1)>0) & (Cont<Iter ))
Error in BusquedaIncremental/SubmitButtonPushed (line 42)
[resultCode, resultX1, resultX2, Z] = busquedas_function(Xo,Delta,Iter,Fun);
Related documentation
228 throw(callbackException);
In workspace belonging to matlab.apps.AppBase>@(source,event)tryCallback(appdesigner.internal.service.AppManagementService.instance(),app,callback,requiresEventData,event) (line 37)
Interrupt while evaluating Button PrivateButtonPushedFcn.
42 [resultCode, resultX1, resultX2, Z] = busquedas_function(Xo,Delta,Iter,Fun);
2 arguments
Xo =
NaN
Yo =
'x*x*x+4*x*x-10'
I checked (hovering over the variables at the paused execution moment) and the function call from app designer is passing the values of Xo, Delta and Iter as NaN , so when it tries to evaluate the f function in Xo its creating the weird matrix we've been seeing!
"Fun" seems to be passing fine for now on the other hand
Im a bit shocked thats the issue, I don't know why its been passing as Nan.
by putting the input as it was before, I mean like this:
Xo = app.XoEditField.Value;
Delta = app.DeltaEditField.Value;
Iter = app.IteraEditField.Value;
Fun = convertStringsToChars(app.FuncionEditField.Value);
it still has the same error message but in a different way, on this way the numeric values pass correctly but it is the inline function that's mapping incorrectly, as it doesnt replace the x by the xo value, and instead it just copies the function as it is. The weird thing is that in the hard-wired function it does work, so that should rule out a compatibility issue, shouldn't it??
here we can see its Y0 and Y1 that are causing the issue because they are not mapping the function.
@Sara Rodriguez - Ahh, I think I see the problem: notice the exta ' on Fun? Can you try your app but don't include the ' in the edit box?
I mean where you typed: 'x*x*x+4*x*x-10'
Instead type: x*x*x+4*x*x-10
a=inline("x*x")
a = Inline function: a(x) = x*x
a(1)
ans = 1
b=inline("'x*x'")
b = Inline function: b(x) = 'x*x'
b(1)
ans = 'x*x'
YEEES it worked.
im so grateful that if it wasnt against the rules I would add a giant annoying blinding gif full of sparkly textures to show my thanks, you truly are a lifesaver. I can't believe it was something so trivial yet it never crossed my mind.
Thank you so much! Words can't describe my gratitude, I'll forver treasure this knowledge in my mind from now on and I'll be more careful in the future!
Ah Sara I feel horrible that I led you down the wrong path to begin with, it's been forever since I've seen someone using inline, I should have spotted it right away! (but ' is so small!)
Nooo, don't worry, I barely know what I'm doing and you've been very patient explaining what may be wrong with examples and everything! I'm very grateful!

Sign in to comment.

More Answers (0)

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Products

Release

R2021b

Community Treasure Hunt

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

Start Hunting!