how differentiate symbolic function has a variable name matlab - matlab

please,
I want matlab to generate dynamic variable name as many as specified number
ex,
generate F1,F2,...
but the problem that I want to differienate the unspeceified number
I use
for k = 1:number
eval(diff(['F', num2str(k)]))
end
so what's wrong?

You should start your code with:
f=sym('f',[1,number])
this creates symbolic variables f1... organised in an array.
for k = 1:number
diff(f(k))
end
Avoid eval whenever possible. For reasons read doc eval.

Related

Making symbolic functions without hard-coding in MATLAB

I want to make symbolic functions theta1(t), theta2(t), theta3(t),...,thetaN(t) where N is some parameter I can define in MATLAB. I know that I can use something like sym('theta',[1 N]) to get [theta1, theta2, theta3,..., thetaN]. However, how can I do the same thing with theta being a function of t? The way to hard-code it would be like syms theta1(t) theta2(t) theta3(t) ... thetaN(t), but I want to make this general.
I do not want to directly use the sym command here because "support of character vectors that are not valid variable names and do not define a number will be removed in a future release", meaning something like sym('theta1(t)') would not be valid in future releases.
Any suggestions?
Figured part of it out. I could do something like the following
for i = 1:N
syms(strcat('theta',num2str(i),'(t)'))
end
However, if I want to assign a variable that contains all the symbolic expressions I'm still stuck. If I try
for i = 1:N
my_array(i) = syms(strcat('theta',num2str(i),'(t)'))
end
I get Error using syms (line 133). Using input and output arguments simultaneously is not supported. It works if I use sym instead of syms, but this leads to the warning I mentioned in my original post.

Matlab: assign variable only if not already existing?

This is the matlab equivalent to this question. Essentially, I'm wondering if there is a way to avoid explicitly writing the exists check for a variable before assigning it.
You may use
persistent varname
if isempty(varname)
varname=heavyComputation()
end
This will only recompute varname at startup and after each clear fun and clear all.
Why avoid exist? This is exactly what it is for:
if ~exist('t', 'var')
t = 1
end
For your specific use case, if you don't want a certain variable to be recalculated, save it into a MAT-file and check for its existence before recalculating. For example, if you are calculating A, then you can do something along the lines of:
if exist('mycalcs.mat', 'file')
load('mycalcs.mat', 'A') %// Load precalculated A
else
A = do_some_calculations(); %// Calculate A
save('mycalcs.mat', 'A'); %// Save it to a workspace file
end
This allows you to rerun the script without repeating calculations, even after clearing the variable in question or closing MATLAB altogether.
You could use the syntax who(variable_name) to check if the variable exists in the workspace as shown here: http://www.mathworks.com/help/matlab/ref/who.html

make matlab variable in workspace as global

In the workspace I make a matrix .
Now I can access the variable in script. Like doing Variable(2) will return 4.
But inside a function like
function y= getvariable(x)
y=Variable(x)
end
I get error
y=getvariable(2)
??? Undefined function or method 'Variable' for input
arguments of type 'double'.
Error in ==> getvariable at 3
y=Variable(x)
So how to make the Variable matrix global so that I can access it through any function?
Although you could use globals
>> global Variable = rand(50,12);
...
function y = getvariable(x)
% Always needed
global Variable;
% Here ya go
y = Variable;
end
the MUCH better alternative is to use
function x = getvariable(x)
% no body needed
end
which you call as
>> y = getvariable(Variable);
(Of course, for this contrived example, this would just be equal to
>> y = Variable;
)
Although there are some legitimate use cases for global variables, in general they tend to spaghettify your code and make it far more bug-prone and much harder to debug. Have a read on the subject.
As #rody suggested, pass the matrix and the x inside the function
I am just giving an example to make things clear.
Like you want to access the 10th element of Variable matrix, so make the function as
function y= getvariable(matrixname,no)
y=matrixname(no)
end
If you want to access 3rd element of Variable, so you type
y=getvariable(Variable,3)
you will get 3rd element
call global Variable before you define it in your workspace
call global Variable before you use it in your function
However I suggest you think of other ways to pass variables to your function, as globals might cause difficulties during debugging.

Cast entire matlab workspace to some class

I'm looking for a way to cast the entire workspace in matlab to some class (say double).
For simplicity, lets just assume that only "simple" classes are present in the workspace (no cells or structs). Of course I can go line by line and change each variable, x=double(x) , but that's not practical if I have several 100's of variables. This is what I've wrote so far:
% # generate some variables of different classes
a1=int32(120);
a2=single(rand(10));
a3=double(rand(20));
a4=(rand(5)>0.5); %# logical
% # collect workspace variables using `whos`
ws=whos;
for ii=1:size(ws,1)
[ ? ] = double(eval(ws(ii).name))
end
The last line double(eval(ws{1,ii})) performs the casting, but how should I assign it's output automatically to the original variables names?
You are also welcome to suggest an alternative way to cast all variables of the workspace, if you can think of one...
Interesting question (+1). What about this?
ws = whos; %# Obtain workspace
for n = 1:size(ws,1)
eval([ws(n).name, ' = double(', ws(n).name, ');']); %# Assign to double
end
This worked for me on R2012b. The trick is to alter the variable type and assign it with one call to eval.

Concatenate equivalent in MATLAB for a single value

I am trying to use MATLAB in order to generate a variable whose elements are either 0 or 1. I want to define this variable using some kind of concatenation (equivalent of Java string append) so that I can add as many 0's and 1's according to some upper limit.
I can only think of using a for loop to append values to an existing variable. Something like
variable=1;
for i=1:N
if ( i%2==0)
variable = variable.append('0')
else
variable = variable.append('1')
i=i+1;
end
Is there a better way to do this?
In MATLAB, you can almost always avoid a loop by treating arrays in a vectorized way.
The result of pseudo-code you provided can be obtained in a single line as:
variable = mod((1:N),2);
The above line generates a row vector [1,2,...,N] (with the code (1:N), use (1:N)' if you need a column vector) and the mod function (as most MATLAB functions) is applied to each element when it receives an array.
That's not valid Matlab code:
The % indicates the start of a comment, hence introducing a syntax error.
There is no append method (at least not for arrays).
Theres no need to increment the index in a for loop.
Aside of that it's a bad idea to have Matlab "grow" variables, as memory needs to be reallocated at each time, slowing it down considerably. The correct approach is:
variable=zeros(N,1);
for i=1:N
variable(i)=mod(i,2);
end
If you really do want to grow variables (some times it is inevitable) you can use this:
variable=[variable;1];
Use ; for appending rows, use , for appending columns (does the same as vertcat and horzcat). Use cat if you have more than 2 dimensions in your array.