trouble with my octave function - matlab

I think I am missing something very basic here
function F = non_iter(x,kc,kw)
F = [x(6)*x(4)*kc-3*x(2);
x(2)*x(5)-kw*x(6)*x(3);
x(2)+x(6)-1;
x(1) -7.52;
x(6)+2*x(4)+2*x(2)+x(3)-4;
x(3)+x(5)-8];
end
when I call this, like
fu = non_iter(x,kc,kw)
It says vertical dimension mismatch (3x1 vs 1x2)
x is supposed to be a row vector of length 6 and kc and kw are scalars.
I have other functions with vector and scalar arguments but they don't return a column vector.
I tried with this function in separate file as well as make it inline with # operator.

This version is working for me on Matlab.
function F = non_iter(x,kc,kw)
F = [x(6)*x(4)*kc-3*x(2);
x(2)*x(5)-kw*x(6)*x(3);
x(2)+x(6)-1;
x(1)-7.52;
x(6)+2*x(4)+2*x(2)+x(3)-4;
x(3)+x(5)-8];
end
In the 4th row of F the white space is treated as a separator for two entries, it should be removed. Additionally, there is an unnecessary bracket.

Related

Write a function file that returns the sum of the positive components and the sum of the negative components of the input vector

Question: Write a function file that returns the sum of the positive components and the sum of the negative components of the input vector.
This problem has to be done in MATLAB but I am completely new in MATLAB? Can anyone give idea how to do this?
Attempts:
V= input(Enter a vector)
function [Ps, Ns] = mysmallfunction(V)
Ps== sum(V(V>0));
Ns= sum(V(V<0));
end
I don't know whether it will work or not.
You pretty much had it. Below is a script that'll guide you through passing the arguments and calling the function. A small issue was the double == for the assignment of Ps within the function (simply use one = unless it's for a conditional statement). To call/test the function simply use the line [Ps, Ns] = mysmallfunction(V); above your function definition (alternatively can put function definitions in separate scripts).
V = input("Enter a vector: ");
%Function call%
[Ps, Ns] = mysmallfunction(V);
%Printing the results to the command window%
fprintf("The positive numbers sum up to %f\n",Ps);
fprintf("The negative numbers sum up to %f\n",Ns);
%*******************************************************************************************************%
%FUNCTION DEFINITION (this can alternatively go in a separate script named: mysmallfunction.m)%
%*******************************************************************************************************%
function [Ps, Ns] = mysmallfunction(V)
Ps = sum(V(V>0));
Ns = sum(V(V<0));
end
Command Window (sample input)
Important to include the square brackets, [] in this case when inputting the vector.
Enter a vector: [1 2 3 -2 -5]

How do functions really work in MATLAB?

function [dhdt, x] = velocity(t, h)
dhdt = -9.8 * t;
x = 4 * t;
end
So this is basically my function (with filename velocity.m). At first I thought that what's between the brackets [] would be the output. When I typed in the Command Window I only got one answer.
velocity(1)
%// -9.8
I expected to get a two-element vector containing both dhdt and x
velocity(1)
%// -9.8 4
Why is this?
Matlab only displays one output if you don't store them to variables... Type [dhdt, x] = velocity(1) and you'll see both values, as well as having them stored to variables.
Also, you only get away in this case with not providing the h parameter because it's not used in the function. If you used h in velocity() and called velocity(1) it would break.

matlab can't use dot operator on object

I came across a weird problem today while practicing using classes in MATLAB. It seems like MATLAB can't parse parentheses around an object.
I created a user-defined class named vector that has various attributes: magnitude, angle, length in the x and y directions. I overloaded the unary minus operator so that I can have
a = vector(5,50) % creates a vector with magnitude 5 and angle 50 (in degrees)
a.ang % prints the angle
b = -a
b.ang % 230 degrees
This is all fine and good, but say that I want to find the angle of the -a in one line. You'd expect something like
(-a).ang
to work but instead I get
(-a).ang
|
Error: Unexpected MATLAB operator.
I can't use
-a.ang
either because the dot operator has higher precedence than the minus. Any explanation of why matlab can't parse parentheses around an object?
EDIT: Here's the vector class that I created.
classdef vector
properties
mag
ang % in degrees
x
y
end
methods
function v = vector(mag,ang)
if nargin == 2
v.mag = mag;
v.ang = ang;
v.x = mag*cosd(ang);
v.y = mag*sind(ang);
end
end
function res = plus(u,v)
x = u.x + v.x;
y = u.y + v.y;
res = vector(norm([x,y]), atan2d(y,x));
end
function res = minus(u,v)
x = u.x - v.x;
y = u.y - v.y;
res = vector(norm([x,y]), atan2d(y,x));
end
function res = uminus(v)
res = vector;
res.x = -v.x;
res.y = -v.y;
res.mag = v.mag;
res.ang = mod(v.ang+180,360);
end
end
end
I think I've found the answer. In general, Matlab does not support two sets of parentheses chained together because it could either be an indexing or a function call.
MATLAB's parser is limited, partly for historical reasons. It has never
been possible to do something like f(4)(1) because of the ambiguity. Does it mean that f(4) is a function handle and then we want to pass 1 into that function or does it mean that f is a function, we pass 4 into that function, it returns a vector and then we index into the first element of that? Well, the parser doesn't know either. It could be defined, but it hasn't up till now.
Source: https://www.mathworks.com/matlabcentral/newsreader/view_thread/280225
Also, once I had realized that the two side-by-side parentheses were the problem, it seems that the main workarounds are either:
Use the SUBSREF function to explicitly evaluate the parentheses
Define your own anonymous function to perform the indexing and array handling for you.
Those workarounds are explained in the first two answers in the below link.
How can I index a MATLAB array returned by a function without first assigning it to a local variable?
Thanks for looking over my question guys!
I cannot replicate vector function but for a simple structure like this
a.ang=[2,4,6,8]
what you need is
-a.ang
instead of
(-a).ang
which will reproduce the error you mentioned

Display expression and result of calculation in MuPad

Imagine I define two variables within a MuPad Notebook:
x:=2;
y:=5
For the product
z=x*y
I get displayed:
And if I use hold, I can get the expression:
z=hold(x*y)
But now I'd like to have both, the expression displayed and the result. The two options which appeared logical to me, do not worK:
z=hold(x*y);z
and
z=hold(x*y);eval(z);
How can I get displayed the expression AND the result?
If in two lines it would be alright, but I'd prefer in one line like:
z = x y = 10
I tried some combinations with print, expr2text, hold and _concat but couldn't find a convincing solution to get the desired result. But there is an explanation why the second line just returns z and not 10.
Assignment vs. Equation
z is the result in the second line because you didn't assign something to z yet. So the result says that z is z. In MuPad = is part of an expression. The assignment operator is := and therefore not the same as in Matlab. The only difference between them is the colon.
Writing an equation
For writing an equation, we use = as part of the expression. There is an equivalent function: _equal. So the following two lines generate the same result:
x+y = 2
_equal(x+y, 2)
Assign value to x
For an assignment we use := (in Matlab this would be only =). There is an equivalent function: _assign. So again, the following two lines generate the same result:
x := value
_assign(x, value)
Assign the equation x+y = 2 to eqn
Here we can clearly see the difference:
eqn := x+y = 2
_assign(eqn, _equal(x+y, 2))

Matlab: Command Line Inputs for an Eigenfunction Solver (Numerical Method)

I've got some code to numerically solve for eigenvectors:
function[efun,V,D] = solveeig(n,xmax,i)
for j=1:i
%The first and second derivative matrices
dd = 1/(xmax/n)^2*(-2*diag(ones(n,1))+diag(ones(n-1,1),1)+...
diag(ones(n-1,1),-1));
d = 1/(xmax/n)*((-1*diag(ones(n,1)))+diag(ones(n-1,1),1));
%solve for the eigenvectors
[V,D] = eig(-dd-2*d);
%plot the eigenvectors (normalized) with the normalized calculated
%eigenfunctions
x = linspace(0,xmax,n);
subplot(i,1,j);
plot(x,V(:,j)/sum(V(:,j)),'*');
hold on
efun = exp(-x).*sin(j*pi*x/xmax);
plot(x,efun/(sum(efun)),'r');
shg
end
end
i is supposed to be the first i eigenvectors, n is the dimension of the
matrices (the number of pieces we discretize x into), xmax is the upper limit of the range on which the fxn is defined.
I'm trying to run this from the command line (as: "solveeig # # #", where the number signs correspond to i, n, and xmax) but no matter what I seem to put in for i, n, and xmax, I get "For colon operator with char operands, first and last operands must be char."
What should I be writing on the command line to get this to run?
Using the command syntax interprets the arguments as strings
For fuller details see the documentation but in short:
Calling
myFun myVar1 6 myVar2
is equivalent to calling
myFun('myVar1','6','myVar2')
and not the desired1
myFun(myVar1,6,myVar2)
In the first cases the function will receive 3 strings (text)
In the second the function will receive the data stored in myVar1 myVar2 and the number 6
The specific error you received is caused by line 2 for j=1:i here i is a string. This error is a merely consequence of the way the function has been called, the line itself is fine2.
How to get it to work
Use function syntax: in the command window something like:
solveeig(n,xmax,i)
If command syntax is absolutely required ( and I can't think why it would be) the much less favourable alternative would be to parse the strings inputted in command syntax. To convert the numbers into numeric formats and use evalin/assignin on the passed variable names to pull variables in from the caller
1As mentioned in comments by patrik
2meaning it won't error, however i and j as variable names is another matter