Trying to develop closed form solutions of second order DE - matlab

Basically, I have this function in matlab:
function yy = homo2nd(tt,polycc,y0,v0)
rr = roots(polycc);
cc = [1 1; rr(1) rr(2)\[y0; v0]];
yy = cc(1)*exp(rr(1)*tt) + cc(2) * exp(rr(2)*tt);
yy = round(yy,8);
end
I understand that roots takes the roots of an array signifying the coefficients of the left side of the equation. I feed roots and argument like [1 1 1] and it spits out the eigenvalues of that function.
From there I am lost.
I define tt in the command shell like this:
tt = linspace(0,2*pi,100).
I call homo2nd and feed it arguments (tt,[1 1 1], 1, 1)
When I try to feed roots the argument [1 1 1] like I said I get this error:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
I just need help interpreting the code. Why are the arrays horizontally mismatched?

The error is occuring on this line
cc = [1 1; rr(1) rr(2)\[y0; v0]];
So let's look at this, the 1 1 is fine, it's saying there's a row vector [1,1].
The next part is where the error occurs, the ; moves us to a second row. The first element of that row is rr(1), this is fine.
However, the second element rr(2)\[y0; v0] is using the mldivide command and the result of this isn't a single element, hence the error.

Related

How to assign values to variables in a handle function?

This is simplified but take as an example the following MATLAB function handle:
F = #(x)[x(1)-x(2);x(2)-x(3)]
The system has of course has many solutions. Is it possible to obtain a solution for a function like this one after substituting at least one variable? For example, substituting x(3)=1 the function would become:
G = #(x)[x(1)-x(2);x(2)-1]
And a solution for the other variables can be obtained. I use fsolve and it works quite well for the system of equations I have. Of course what I need to do can be done using the Symbolic Toolbox, but calling it in a big for loop makes it too slow to use for my code.
I'm trying to come up with some code that can return G given F and a set of indices in x to replace with given values.
What you're basically asking to do is have G call F with values in x reassigned based on a logical replacement index index and a set of replacement values values, which is doable but messy since anonymous functions can only have a single executable statement.
The solution is similar to what is done in this answer, but instead of using the functional form for subscripted reference we'll need to use the functional form for subscripted assignment: subsasgn. Here's what it would look like:
F = #(x)[x(1)-x(2); x(2)-x(3)];
values = [3 2 1];
index = logical([0 0 1]);
G = #(x) F(subsasgn(x, struct('type', '()', 'subs', {{index}}), values(index)));
And here's a test:
>> F([3 2 3])
ans =
1
-1
>> F([3 2 1]) % Replace the last element by 1
ans =
1
1
>> G([3 2 3]) % G handles replacing the last element by 1
ans =
1
1

Error in creating a volcano plot in MATLAB

I am a complete newbie to MATLAB and the first task I have is to create a volcano plot. I have been using the documentation to understand about it and get started.
I tried to run it on dummy values -
a=[1 2 3]
b=[4.6 2.7 4.5]
c=[0.05 0.33 0.45]
And then I ran -
SigStructure = mavolcanoplot(a, b, c)
My understanding is that a represents the gene expression values for condition 1, b for condition 2, and c is the list of p-values for the 3 data points in a and b.
However running this code gives me the error -
Index exceeds matrix dimensions.
Error in mavolcanoplot (line 127)
appdata.effect = X(paramStruct.goodVals) - Y(paramStruct.goodVals);
Error in volc (line 4)
SigStructure = mavolcanoplot(a, b, c)
Can anyone explain where I am going wrong?
You're encountering an issue because you are using row vectors.
Inside the mavolcanoplot function (you can see the file by typing edit mavolcanoplot in the command window) there is a local function for checking the inputs, called check_inputdata.
Your data passes all of the validation checks, and then encounters this section:
% Here, 'X' and 'Y' are the local names for your inputs 'a' and 'b'
% Below code is directly from mavolcanoplot.m:
% Handle the matrix input. Use its mean values per row
if size(X, 2) > 1
X = mean(X,2);
end
if size(Y, 2) > 1
Y = mean(Y,2);
end
This reduces your inputs to their mean. Later in the main function (line 127) you encounter the error as described, where paramStruct.goodVals is a 3 element array, which is now trying to index a 1 element array and fails!
This is basically a lesson in debugging and reading the documentation, which states
DataX, DataY: If a [...] matrix, each row is a gene, each column is a sample and an average expression value is calculated for each gene.
You should use one of these equivalent methods to create column vector inputs
a=[1 2 3].'; % Using transpose (.') to create a column vector from a row vector
b=[4.6; 2.7; 4.5]; % Creating a column vector using the semi-colon operator to end each row
c=[0.05
0.33
0.45]; % Using actual code layout to create a column vector

Matlab Function with Varying parameters

I need help figuring out how to code the following problem. Any help would be greatly appreciated!
Create a function that will take a vector/array input for x (1 by n) and a scalar input for a, and produce the output defined by the following equation:
y(x,a)=((xsin(ax-2))/(sqrt(1+(ax)^2)
-π ≤ x ≤ π
a={.5 1 1.5 2}
The equation must be vectorized in terms of x and the output from the function is the array y which has the same dimension as the array x.
Write a script that calls this function to compute y(x,a) for the range of x defined above and each value of the parameter a. Results should be stored in a solution matrix using a different row of the solution matrix for each value of a.
So far for my function I have:
function [y] = part1(a,x)
y=((x*sin(a*x-2))/(sqrt(1+(a*x).^2)));
end
I'm not sure how to output this into the solution matrix
For my script I have:
%%
clear,clc
a={0.5 1 1.5 2};
x=-pi:0.1:pi;
for
part1(x,a)
end
I'm getting the following errors when I run this now:
Undefined function 'mtimes' for input arguments of type 'cell'.
Error in part1 (line 4)
y=((x*sin(a*x-2))/(sqrt(1+(a*x).^2)));
Error in labtest2 (line 8)
y(i,:)=part1(x,a(i));
EDIT
I've made some changes and am still getting some errors that I cannot resolve.
Here is my full code for function followed by full code for script:
Function
function [y] = part1(x,a)
nx=numel(x);
na=numel(a);
y=((x.*sin(a.*x-2))./(sqrt(1+(a.*x).^2)));
size(y)=[nx na]
end
Script
%%
clear,clc
a={0.5 1 1.5 2};
x=-pi:0.1:pi;
for i = 1:length(a)
y(i,:)=part1(x,a(i));
end
Errors
Undefined function 'times' for input arguments of type 'cell'.
Error in part1 (line 6)
y=((x.*sin(a.*x-2))./(sqrt(1+(a.*x).^2)));
Error in labtest2 (line 8)
y(i,:)=part1(x,a(i));
The reason you're getting Undefined function 'times' for input arguments of type 'cell' is because your variable a is a cell array. You need to change your assignment of a from
a={0.5 1 1.5 2};
to
a=[0.5 1 1.5 2];
which will make it just a normal array. Alternatively, you need to reference it with cell array notation: a{i} instead of a(i).
You're almost there. Note that you've written
function [y] = part1(a,x)
but you call it in your script as
part1(x,a)
so you should probably correct that.
A few things jump out at me:
You never assign the output of part1(x,a) to anything. You're told that
Results should be stored in a solution matrix using a different row of the solution matrix for each value of a.
What I take this to mean is that the 1st row corresponds to part1() evaluated for the 1st element of a. Since we're operating on x which is a vector, that row will have multiple columns. Your output is indeed a matrix. In your case, length(-pi:0.1:pi) == 63, therefore size(y) == [4 63], where y is your output matrix.
Your for loop is backwards. You're told to accept scalar a and vector x. Therefore, your script should be something like:
a = 0.5:0.5:2;
x = -pi:0.1:pi;
for i = 1:length(a)
y(i,:) = part1(x, a(i));
end
Note the use of length and the : operator. I want to iterate between 1 to length(a) (in this case, length(a) == 4) so that I can use the current a(i) value as an index into my output matrix, y. The : operator in y(i,:) signifies "The ith row and all columns of y will take the value output by part1(x,a(i))."
Your function needs to be changed up for element-by-element operations. Notice that, for instance, x*sin(a*x-2) works for scalar x but not vectors. This is because x is a vector and sin(a*x-2) is also a vector (since the sin call will operate element-by-element and a is a scalar). Trying to multiply two vectors together will result in errors since MATLAB will try to perform a matrix multiplication. Resolve this by replacing * with .*. This way it is unambiguous that you are going to multiply these two vectors element-by-element. You'll also need to change / to ./.
On another note, thank you for attempting to do your homework before asking SO for help. We've been getting a huge influx of questions from students that have made no attempt to do their own work before dumping it on us, so it's refreshing that we regulars of the MATLAB tag get to actual help out instead of telling people to do their own work.
Finally got the whole thing worked out.
Function
function [y] = part1(x,a)
y=((x.*sin(a.*x - 2))./(sqrt(1 + (a.*x).^2)));
end
Script
%%
clear all;
clc;
close all;
x=[-pi:.1:pi];
a=[.5:.5:2];
for i=1:length(a)
y(i,:)=part1(x,a(i));
plot(x,y)
end
Sol=[y]

Can I specify nargout as part of a MATLAB function call?

The problem:
I want to index into the result of a function call that returns a variable number of output arguments without storing the result in a temporary.
getel = #(x,i) x(i); #% simple anonymous function to index into a vector
x = zeros(2,2,2);
row = getel(ind2sub(size(x), 8), 1) #% desired: 2 (row 2)
#% actual: 8 (linear index)-because ind2sub is returning 1 value only
[row col dep]=ind2sub(size(x),8) #% row=2, ind2sub returning 3 values
Example usage:
x(1).val1 = [1 2 3];
x(1).val2 = [2 1 2];
x(2).val1 = [2 1 2];
x(2).val2 = [1 0 0];
#% The normal way I would do this, with a temporary variable
[~,ind] = min(x(1).val2); #% ind=2
v(1) = x(1).val1(ind);
[~,ind] = min(x(2).val2); #% ind=2
v(2) = x(2).val1(ind);
#% I'd like to be able to do this with arrayfun:
v = arrayfun(#(s) s.val1(min(s.val2), x);
-------^ returns value of minimum, not index
The above arrayfun doesn't work - the form of min that is called returns one output: the minimum value. To make it work right, one option would be the following hypothetical function call:
v = arrayfun(#(s) s.val1(getoutputnum(2, 2, #min, s.val2)), x);
hypothetical function -----------^ ^ ^ ^-func ^--func args
which form (nargout) of func ---| |- which arg to return
I realize that for the above scenario, I could use
s.val1(find(s.val2==min(s.val2),1,'first'))
or other tricks, but that isn't possible in all cases.
In the case of ind2sub, I may want to know the index into a particular dimension (columns, say) - but the 1-output form of the function returns only a linear index value - the n-dimensional form needs to be called, even if the value of dimension 1 is what I care about.
Note: I realize that writing a function file would make this trivial: use ~ and the [out] = func(in) form. However, when writing scripts or just on the command line, it would be nice to be able to do this all within anonymous functions. I also realize that there are undoubtedly other ways to get around the problem; I would just like to know if it is possible to specify which form of a function to call, and perhaps which output number to be returned, without using the out=func(in) syntax, thus allowing functions to be nested much more nicely.
Could you do something like this?
In its own file:
function idx=mymin(x)
[~,idx] = min(x);
In your code:
v = arrayfun(#(s) s.val1(mymin(s.val2), x);
Might have syntax errors; I don't have MATLAB on the computer I'm writing this on. The idea is there though: just wrap MATLAB's min and capture the second argument, which is the logical indexing for the position of the minimum value in x.
I can get ind2sub() to return the variable number of args like this:
x = zeros(2,2,2);
c = cell(ndims(x),1);
[c{:}] = ind2sub(size(x), 8);
The c cell array will now have the 3D indices c = {2;2;2}.
[c{:}] = ind2sub(size(x), 2);
would produce c = {2;1;1}.
Is this what you were looking for?

Can't output multidimensional matrix in Matlab function in Simulink

For example I have function that creates matrix 2x2 : [1 2; 3 4]
I have such simple function:
function[result] = Rho(x)
// I've tried and so:
result = [1 2; 3 4];
// And so:
result(1,1) = 1;
result(1,2) = 2;
result(2,1) = 3;
result(2,2) = 4;
In Matlab window i see right result:
>> Rho(1)
ans =
1 2
3 4
But in Simulink I always get [1;2;3;4]. Where is my mistake?
P.S. I forgot to remove argument x of function, because in real function I make matrix depending on argument x. But it doesn't play role in our example
The problem you are having is likely due to the parameter settings for your MATLAB Function block (now called an Interpreted MATLAB Function block in newer versions). Take a look at the Parameters Dialog Box for that block:
Note that you will want to set the Output dimensions to 2 and uncheck the Collapse 2-D results to 1-D check box. If this is left checked, then your 2-by-2 matrix will be turned into a 1-D array by extracting values along each column from left to right, which ends up being [1 3 2 4] in your example.
Once you apply the above changes, then all you should have to do is resize your Display block so that it shows your 2 rows and 2 columns.