Error running matlab code after compiling - matlab

It looks like this has been asked many times, but none of the past posts seem to solve my question. All those had to do with matrix/vector while my code does not have any of these, just simple variables. It takes three variables as arguments. It works perfectly fine within the Matlab environment. I only got the error when I compiled it with mcc -m Normal.m and tried to run with the executable like this "./Normal 1 5 0.5". The complete error message is:
Error using /
Matrix dimensions must agree.
Error in Normal (line 4)
MATLAB:dimagree
It is complaining about line 4: N=2/dt, what is wrong with this?
Here is the code:
function val=Normal(l1,l2,dt)
const=(l2/l1-1);
N=2/dt;
S=1.0/sqrt(l2/l1);
Z(1)=S;
for i=2:N
t= -1+(i-1)*dt;
Z(i)=1.0/sqrt(const*t*t+1);
S=S+2*Z(i);
end
Z(21)=1.0/(l2/l1);
S=S+1.0/sqrt(l2/l1);
val=dt*S/2;
end

But dt is not a scalar when passed into the standalone through the command ./Normal 1 5 0.5. It is a character array with 3 elements ('0', '.','5')!
When passing numerical arguments to a standalone, they are passed as strings. Thus, inside the function, you need to convert '0.5' into a double, and similarly for l1 and l2:
dt = str2num(dt);
l1 = str2num(l1);
l2 = str2num(l2);
Note that you can use isdeployed to determine at runtime if the function is a standalone:
if isdeployed, dt = str2num(dt); end
And you might need to display the result:
if isdeployed, disp(val); end
Result:
>> system('Normal 1 5 0.5');
1.4307
>> Normal(1,5,0.5) % .m function for comparison
ans =
1.4307

Related

MATLAB Optimization toolbox example

https://www.mathworks.com/help/optim/examples/banana-function-minimization.html
fun = #(x)(100*(x(2) - x(1)^2)^2 + (1 - x(1))^2);
options = optimset('OutputFcn',#bananaout,'Display','off');
x0 = [-1.9,2];
[x,fval,eflag,output] = fminsearch(fun,x0,options);
title 'Rosenbrock solution via fminsearch'
Fcount = output.funcCount;
disp(['Number of function evaluations for fminsearch was ',num2str(Fcount)])
disp(['Number of solver iterations for fminsearch was ',num2str(output.iterations)])
What is #bananaout here?
This is giving me the following error,
??? Error using ==> feval
Attempt to execute SCRIPT bananaout as a function:
C:\Users\admin\Desktop\bananaout.m
Error in ==> callAllOptimOutputFcns at 12
stop(i) = feval(OutputFcn{i},xOutputfcn,optimValues,state,varargin{:});
Error in ==> fminsearch>callOutputAndPlotFcns at 464
stop = callAllOptimOutputFcns(outputfcn,xOutputfcn,optimValues,state,varargin{:})
|| stop;
Error in ==> fminsearch at 199
[xOutputfcn, optimValues, stop] =
callOutputAndPlotFcns(outputfcn,plotfcns,v(:,1),xOutputfcn,'init',itercount, ...
Error in ==> test_optim at 9
[x,fval,eflag,output] = fminsearch(fun,x0,options)
As per the doc, Output Functions are called by the optimizer at every time step, enabling you to do things like plot the progress of the optimization.
In your case you get an error because bananaout seems to be a script when it needs to be a function (with specific inputs - see the doc for their details). Did you happen to save the example code in a script called bananaout? If so, rename the script.
You can see a list of all m-code that you have that are called bananaout by executing the following:
>> which bananaout -all
One of them will be the function that the example should be calling, while another will be the one that you have created and need to rename/remove.

Matlab says 'find' is not defined in a function [duplicate]

This question already has an answer here:
MATLAB error: "previously appeared to be used as a function or command"
(1 answer)
Closed 8 years ago.
In my command window, I can execute find([0 1 0]), but when I run find in a function, as in x = find([0 1 0]), the compiler tells me that find isn't defined. Why might that be?
The error is:
??? Error: File: frequentTuples.m Line: 12 Column: 21
"find" previously appeared to be used as a function or command, conflicting with its
use here as the name of a variable.
A possible cause of this error is that you forgot to initialize the
variable, or you have initialized it implicitly using load or eval.
and here's the code. The error occurs on the second line of the for loop.
function [ tuples ] = frequentTuples( k, candidates, transactions, min_support )
%FREQUENTTUPLES Get frequent itemsets of size k
% Detailed explanation goes here
candidate_tuple_is_frequent = zeros(size(candidates, 1));
for i = 1:size(candidates, 1)
columns_of_candidate_items = transactions(:, candidates(i, :));
indices_of_transactions_containing_all_items = find(sum(columns_of_candidate_items') == k);
candidate_tuple_is_frequent(i) = size(indices_of_transactions_containing_all_items) >= min_support;
end
tuples = candidates(find(candidate_tuple_is_frequent, :));
end
Ah, I see your problem now. You have a misplaced bracket on line 13. You have
tuples = candidates(find(candidate_tuple_is_frequent, :));
When you should have
tuples = candidates(find(candidate_tuple_is_frequent), :);
You're trying to call find(candidate_tuple_is_frequent, :), which is trying to treat find as a variable. This means that any other call to find in the function will treat it as a variable, hence your error.

Invoking a function from another which has the same number of inputs and outputs

I want to call a function in Matlab using another one, which has the same number of inputs and outputs. In fact, those inputs and outputs have the same name.
Example:
function [a,b] = gettwo(matrix,string,varargin)
[a,b] = getone(matrix,string,varargin{:});
end
This code produces the following error:
Error in getone(line 3)
aux = 'matrix(varargin{:})';
Output argument "b" (and maybe others) not assigned during
call to "C:\Users\baister\Documents\MATLAB\soft\getone.m>getone".
Error in results (line 4)
[a,b] = getone(matrix,string,varargin{:});
How should I wrap getone?
(The definitive function will have more lines than those shown in this post.)
Thanks.
The general wrapping for variable number of outputs should work like this:
function [varargout] = gettwo(matrix,string,varargin)
[varargout{1:nargout}] = getone(matrix,string,varargin{:});
end
You'll get the same error as above though, in case you do
[a,b] = gettwo(...);
and getone returns only 1 argument.

x = disp(y) : "Too many output arguments"

I'm looking for a completely general way to convert any value to a string in MATLAB.
Basically, I want to be able to write something like
x = disp(y);
The above fails with the error Too many output arguments. (I was not able to find the source code for disp.)
Is there a single MATLAB function for converting any value into a string?
(Note that this function should behave like the identity when passed a string.)
Basically I'm looking for MATLAB's equivalent of Python's str. I thought it might be char, but (for example) char(Inf) fails to produce anything like the string 'Inf'. (Note: that was just an example. It does not begin to cover all the possibilities.)
pm89's answer has the right idea, but doesn't work because evalc requires a string as input. I suggest making your own function like so:
function str = anything2string(thing)
str = evalc('disp(thing)');
It works for anything that Matlab can display:
>> anything2string(3)
ans =
3
>> anything2string(Inf)
ans =
Inf
>> anything2string('hi')
ans =
hi
>> anything2string(1:4)
ans =
1 2 3 4
It's not quite the same as Python's str, but num2str works with Inf and handles strings as input.
num2str(Inf)
ans = Inf
num2str('some string')
ans = some string
You could get the exact same string as you see in your command window using evalc (evaluate and capture the result):
x = evalc('disp(y)'); % y could be anything displayable by Matlab!

MATLAB: If Statement inside loop is not executing, nor printing to the screen

So, we are trying to execute the following code. The two if statements are executing, however, the inside if statements are failing to execute (we verified this by not suppressing the output). Is there a reason why? Or are we just not able to reach this state?
Specifications
The input is as follows: v is a vector of int values and c is a integer. c must be less than or equal to one of the values within v
The problem that we are trying to solve with this algorithm is as follows:
Given a cash register, how does one make change such that the fewest coins
possible are returned to the customer?
Ex: Input: v = [1, 10, 25, 50], c = 40. Output O = [5, 1, 1, 0]
We are just looking for not a better solution but more of a reason why that portion of the code is not executing.
function O = changeGreedy(v,c)
O = zeros(size(v,1), size(v,2));
for v_item = 1:size(v,2)
%locate largest term
l_v_item = 1
for temp = 2:size(v,2)
if v(l_v_item) < v(temp)
l_v_item = temp
end
end
%"Items inside if statement are not executing"
if (c > v(l_v_item))
v(l_v_item) = -1 %"Not executing"
else
O(l_v_item) = idivide(c, v(l_v_item)) %"Not executing"
c = mod(c, v(l_v_item)) %"Not executing"
end
end
If c or v are not integers, i.e. class(c) evaluates to double, then I get the following error message
??? Error using ==> idivide>idivide_check at 66
At least one argument must belong to an integer class.
Error in ==> idivide at 42
idivide_check(a,b);
and the program stops executing. Thus, the inside of the second statement never executes. In contrast, if, say, c is an integer, for example of class uint8, everything executes just fine.
Also: what are you actually trying to achieve with this code?
Try to do this operation on your input data:
v = int32([1, 10, 25, 50]), c = int32(40)
and run again, at least some portions of your code will execute. There is an error raised by idivide, which apparently you missed:
??? Error using ==> idivide>idivide_check at 67
At least one argument must belong to an integer class.
Error in ==> idivide at 42
idivide_check(a,b);
Indeed, idivide seems to require that you have actual integer input data (that is, class(c) and class(v) both evaluate to an integer type, such as int32).