Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
Is there a way to change a function variable to another variable?
for instance, if I have the function:
f = #(s) exp(2-s)
I need to change it to
f = #(t) exp(2-t)
without changing it manually.
With the usual caveats that this is a terrible idea :) let's get a little nuts.
First, we can make the anonymous function f
f = #(s) exp(2-s)
For some sample uses, for sanity
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, save it to a file, using the -v7.3 flag to force an H5 file type
save('tempfile','f','-v7.3')
Matlab can read this file as data. After some exploring, we can see that the function is stored, as an evaluation-ready string, here:
char(h5read('tempfile.mat','/f/function_handle/function'))
% Returns 'sf%0#(s)exp(2-s)'
So, it's easy enough to change, using Matlab's H5 write functions
h5write('tempfile.mat','/f/function_handle/function',uint16('sf%0#(x)exp(2-x)'))
Let's see, did it work?
clear f
load('tempfile.mat')
Now we have the following
f =
function_handle with value:
#(x)exp(2-x)
f(1) % 2.71828182845905
f(10) % 0.000335462627902512
Now, we can see a lot of this data without the file saving business, using the functions function. (So meta)
>> f = #(s) exp(2-s);
>> functions(f)
ans =
struct with fields:
function: '#(s)exp(2-s)'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
This lets you see how Matlab is storing the anonymous function. When debugging, this allows you to see what baggage (stored workspaces and stuff) is associated with the function handle.
However, changes to this structure do not change the actual function handle. I don't know of a way to generate a new function handle from this structure.
Wrap up
[note #1 deleted]
Please, don't ever do this.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to optimize a function with 2 inputs. Trying to use fminsearch but it keeps saying undefined function or variable although it is already defined.
I have already defined the function in a separate script that is in the same directory with my main script. I have a classroom license which includes optimization toolbox and there is no spelling mistake while calling the function.
function o=u(x,y)
%some code here
end
%in a second script
init=[0.1,0.1];
b=fminsearch(o,init);
The error is:
Undefined function or variable 'o'.
From the documentation on fminsearch, the function being minimized must have a single argument and accessed with a function handle (see this related answer).
The error you are getting is because you can't call o and use it as an input to fminsearch() since o is undefined. To get o, you have to first get u(x,y), plus as mentioned, fminsearch requires a function handle as an input.
You have several options that still use your standalone function, u(x,y).
1. Create a function handle
Define a function handle that calls u(x,y) but has a single argument which is a 2 x 1 vector, z = [x; y].
fh =#(z) u(z(1),z(2));
z0 = [1; 2]; % Initial Guess for z = [x; y]
[z,TC] = fminsearch(fh,z0)
2. Change the function and call it directly
The same result is possible with
[z,TC] = fminsearch(#u,z0)
if you redefine u(x,y) to be as follows:
function o=u(z)
x = z(1);
y = z(2);
% your function code here
end
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to define a two variables function g so that g(x,y) be a 2*2 matrix. To do this, I define g(x,y)=[1,1;x,y] but when I put g(1,1) I don't get any answer. How can I evaluate to g?
The code g(x,y)=[1,1;x,y] itself will not do anything. I assume that your expect result will be g=[1,1,1,1]? Therefore you should do as follow:
g=g_func(1,1);
disp(g)
function g=g_func(x,y)
g=[1,1;x,y];
end
It's not that different from the previous answer, but perhaps an anonymous function would meet your needs:
>> g = #(x,y)[1,1;x,y];
>> g(5,6)
ans =
1 1
5 6
Alternatively, if you want g to accept only one input (i.e. a 2-element vector, instead of two scalars), you could do:
g = #(x)[1,1;x(1),x(2)];
% or
g = #(x)[1,1;x(:).'];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i have written a m-function in a script. This function script simulates behavior of a system.
Now i want to implement it in a Simulink Modell. The function has several inputs and several outputs. Actually i find the user-defined functions, but they all have one input and one output.
Do somebody now how i can implement the m.file into the simulink modell with more than one inputs and outputs?
Thank You!
All of the user defined functions allow multiple inputs.
For instance, the MATLAB Function block has a default of:
function y = fcn(u)
y = u;
Which can be changed to have 2 outputs and 3 inputs (for instance) just like any other MATLAB function:
function [out1,out2] = fcn(in1,in2,in3)
out1 = in1;
out2 = in2 + in3;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a set of data in a text file with the format like below. How shall I import the data into MATLAB? Thanks!
{(38.7948,1319,0.8571,119,0),(39.0693,138,0.0897,21,0),(40.7911,63,0.0409,7,0),(103.4512,19,0.0123,5,0),(-26.0424,223,1.0000,28,0)}
{(35.8689,110,0.5093,14,0),(47.7915,41,0.1898,7,0),(59.7489,53,0.2454,7,0),(71.7298,12,0.0556,3,0)}
It's always helpful if you in your question explain what you have tried so far, what the desired result would be or how you inteend to use it. That way the person answering the question don't have to assume a lot of things.
Here I assume that you would like to import each line as a cell with a set of number arrays within.
To get matlab to evalutate the expression correct the parentheses in the brackets need to be replaced
{(1,2),(3,4)}
Error: Expression or statement is incorrect
{[1,2],[3,4]}
ans =
[1x2 double] [1x2 double]
To read the file you could use fopen and then fgetl to get each line. When the result from fgetl isn't a char, the end of the file (EOF) is reached.
% Open file
f = fopen('...path\to\file.txt','r');
C = {};
while true
% Read each line
fStr = fgetl(f);
if ischar(fStr)
% Replace parentheses and evaluate expresission
C{end+1} = eval(regexprep(fStr,{'(',')'},{'[',']'}));
else
% End of file
break
end
end
fclose(f)
Perhaps you need to include some error checks if the data in your file should be formated incorrect. You could also check out other ways to read data, for exmple fread or fscanf
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm considering buying Matlab Home + Optimization module for home use, however I'm not sure it can do what I want it to.
I have an external process (not Matlab) that takes input, runs a process, and produces output. I want to tie in the input and output to Matlab so that Matlab can "optimize" these inputs, completely blind to the discrete process itself. Does Matlab have discrete optimization capabilities, or do all of its optimization functions rely on having internal access to the process itself?
Thanks!
-Stephen
if your external process is capable to assimilate parameters and give response to a external program using any methods eg, command line, or files, yes it is possible just configure your objective function to send and read the parameters and response data to the external process.
For the discrete optimization, the optimization toolbox do not work with discrete optimizations problems, but the documentation give a hint about rounding the parameter inside the objective function and then running again in the responses variable.
for example, this can be a function to optimize a volume of a prism
which is coded in a external program written in python (just for demonstration purpose with single objetive genetic algorithm (ga)):
function f = optim(x)
%Optimization criteria
l = round(x(1));
h = round(x(2));
w = round(x(3));
%String to produce the external proccess call as a system command
commandStr = ['python -c "print ' num2str(l) ' * ' num2str(h) ' * ' num2str(w) ' "'];
%Execute the system command, status = 0 for good execution
[status, commandOut] = system(commandStr);
%Convert the output of the external program from strin to doble and assign as the response of the optimization funcition
f = str2double(commandOut)
Then you can use the optimtool using this funcion as objetive as:
Then export the result to workspace and round() it.
Or make it programmable with a code like this:
function [x,fval] = runOptimization(lb,ub)
options = gaoptimset;
options = gaoptimset(options,'Display', 'off');
[x,fval] =ga(#optim,3,[],[],[],[],lb,ub,[],[],options);
x = round(x)
fval = optim(x)
And run as
[x,fval] = runOptimization([1 1 1],[3 4 5])
NOTE. the round() functions its only to demonstrate how to do discrete optimization as suggested in the documentation