Running octave function prints lines of command name - emacs

Basically I'm running Octave 4.2.1 in Emacs 25.2.1 all within iTerm2 on macOS Sierra and every time I run a function (any function), a list of what look like command names is printed before the answer. I have tried to look up to see if this has been answered, but I'm having trouble describing the output list in a search. Here is the function command:
octave> f(3)
where f is declared as:
octave> function y = f(x)
>y = x + 10;
>endfunction
and the output is:
yes_or_no
ylabel
ylim
yulewalker
x
xlabel
xlim
xor
end
end_try_catch
end_unwind_protect
endfor
endfunction
endgrent
endif
endparfor
endpwent
endswitch
endwhile
endfunction
endfunction
ans = 13
I have tried placing semicolons at the end of every line (because I was unsure if this is function output that could be silenced with a semicolon), but that didn't pan out.
Edit: I have also tried turning off diary because I'm not sure that diary is. Needless to say, did not work out.
Let me know what I can do to stop this output. And if this is a duplicate due to me not having the vocabulary to search for my solution, obviously just mark it and I'll follow the link.
Thanks!

Related

Matlab serial communication inconsistency

I want to control a Prior ProScan II controller and the fitting motorized stage with Matlab R2016b. Manual Tested with R2010b, got the same results. The relevant commands of the stage are VS(page 46), P(p.43), PS(p.44). In a plain terminal, immediately after the stage halts I can issue the P or PS command, returning the current position of the X and Y axes. If done in Matlab prompt, it MIGHT need a second or two to return the proper value, before that it returns 'R' - Probably not the ACK of the previous command as it is returned after init, without any R-ACKed commands issued before. When used in a script in a separate .m file, it can only return 'R'. My code in main.m is as follows:
%Opening serial port
s = serial('COM9');
set(s,'BaudRate',9600,'Terminator','CR'); %Note that CR will be concatenated to all commands
fopen(s);
s %print for debugging
t=1 %loop index
while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Here is code to mess with a joystick that works fine, using VS command
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if button(joy, 3) == 1 %Button3 of joystick should trigger position reading
fprintf(s,'vs,0,0'); %Halt joystick movement
pause(1) %Debouncing
fprintf(s,'p'); %Axe-pos reading command
fgets(s) %Reading the answer
end
%This way to increment follows the skipped parts and is required for timing
if mod(t, 100)==0
fprintf(s,'%s',Command);
t=1;
else
t=t+1;
end
If the segment in if..end is invoked from the Matlab prompt, it works fine in most cases.
>> s = openserial()
%properties as before, skipped to save space
>> fprintf(s,'ps');
>> fgets(s)
ans =
100000,100000
or
>> fprintf(s,'p');
>> fgets(s)
ans =
100000,100000,0
If I Ctrl+C out of the infinite loop but leave the serial open and issue
>> fprintf(s,'p');
>> fgets(s)
ans =
R
returns. Using fscanf() instead of fgets() yields the same results.
Is there any known bug of fprintf() or the ones mentioned above that could cause this? What could I do to succesfully and consistently read within a script? Thank you for any answers.
Solution was to force flush the serial input buffer, flushinput(s) before the line pause(1). For some reason, even fscanf() instead of fgets() didn't flush it. I still don't know why it worked fine outside the script but not within. Additionally, it also worked in a separate script.

Matlab r2016a throwing error [duplicate]

I keep trying to run this and have no idea what is going wrong. I have it saved as test.m. I click run in the editor and in the matlab command window, it states not enough input arguments. I feel like I am missing something totally obvious, but I cannot spot the issue.
function y = test(A, x)
%This function computes the product of matrix A by vector x row-wise
% define m number of rows here to feed into for loop
[ma,na] = size(A);
[mx,nx] = size(x);
% use if statement to check for proper dimensions
if(na == mx && nx == 1)
y = zeros(ma,1); % initialize y vector
for n = 1:ma
y(n) = A(n,:)*x;
end
else
disp('Dimensions of matrices do not match')
y = [];
end
end
It is a function (not an script) and it needs some input arguments to run (in this case A and x), so you cannot hit the run button and expect it to run.
The first way:
Instead you can use the command windows in MATLAB and enter the command:
A = rand(3,3); % define A here
x = ones(3,1); % define x here
test(A,x) % then run the function with its arguments
remember that A and x should be defined properly.
The second way is:
Also you can hit the little triangle besides the green run button (see the figure below), and it will show you another option, type command to run. And
there you can directly enter the same command test(A,x). After that, each time you just hit enter for this function and it runs this command instead of only the test command without any argument.
The third way:
function y = test(A, x)
%// TESTING CODE:
if nargin==0
A = default_value_for_A;
x = default_value_for_x;
end
... %// rest of the function code
This way allows you to "click the play button" and have your function run with no explicit input arguments. However, be advised that such a method should only be used:
When debugging, so as not to allow users to call the function with no arguments if this is not its intended use case.
If your function is not supposed to behave differently for a different number of inputs. See also function overloading in MATLAB based on number of input arguments.

Using Euler's Method in Matlab

First time post here. Pretty frustrated right now working on this assignment for class.
Basically, the idea is to use Euler's method to simulate and graph an equation of motion. The equation of motion is in the form of an ODE.
My professor has already put down some code for slightly similar system and would like us to derive the equation of motion using Lagrange. I believe that I have derived the EOM correctly, however I am running into problems on the Matlab side of things.
What's weird is that using a similar technique on another, seperate EOM, I have no issues. So I am unsure what I am doing wrong.
Here's the code for the part that is working correctly:
close all; clear all; clc;
% System parameters
w = 2*pi;
c = 0.02;
% Time vectors
dt = 1e-5;
t = 0:dt:4;
theta = zeros(size(t));
thetadot = zeros(size(t));
% Initial conditions
theta(1)=pi/2; %theta(0)
thetadot(1)=0; %thetadot(0)
for I = 1 : length(t)-1;
thetaddot = -c*thetadot(I)-w^2*sin(theta(I));
thetadot(I+1)=thetadot(I)+thetaddot*dt;
theta(I+1)=theta(I)+thetadot(I)*dt ;
end
figure(1);
plot(t,theta,'b');
xlabel('time(s)');
ylabel('theta');
title('Figure 1');
zoom on;
% Output the plot to a pdf file, and make it 6 inches by 4 inches
printFigureToPdf('fig1.pdf', [6,4],'in');
% Open the pdf for viewing
open fig1.pdf
Everything runs fine, except Matlab complains about the printFigureToPdf command.
Now, here is the code for the problem that I am having issues with.
close all; clear all; clc; clf
% System parameters
m=0.2;
g=9.81;
c=.2;
d=0.075;
L=0.001; %L is used for Gamma
B=0.001; %B is used for Beta
W=210*pi; %W is used for Omega
%Time vectors
dt = 1e-6; %Time Step
t=0:dt:10; %Range of times that simulation goes through
x=zeros(size(t));
xdot=zeros(size(t));
%Initialconditions
x(1)=0;%x(0)
xdot(1)=0; %xdot(0)
for I = 1 : length(t)-1;
xddot =-1/m*(c*xdot(I)-c*L*W*cos(W)+m*g-3*B*((d+x-L*W*sin(W*t)).^(-4)-(d-x-L*W*sin(W*t)).^(-4)));
xdot(I+1)=xdot(I)+xddot*dt;
x(I+1)=x(I)+xdot(I+1)*dt ;
end
figure(1);
plot(t,x,'b');
xlabel('time(s)');
ylabel('distance(m)');
title('Figure 2');
zoom on;
% Output the plot to a pdf file, and make it 6 inches by 4 inches
printFigureToPdf('fig1.pdf', [6,4],'in');
% Open the pdf for viewing
open fig1.pdf
With this code, I followed the same procedure and is giving an error on line 23: "In an assignment A(I) = B, the number of elements in B and I must be the same."
Like I said, I am confused because the other code worked okay, and this second set of code gives an error.
If anyone could give me a hand with this, I would greatly appreciate it.
Thanks in advance,
Dave
Edit: As suggested, I changed x(I+1)=x(I)+xdot(I+1)*dt to x(I+1)=x(I)+xdot(I)*dt. However, I am still getting an error for line 23: "In an assignment A(I) = B, the number of elements in B and I must be the same."
Line 23 is: xdot(I+1)=xdot(I)+xddot*dt;
So, I tried adjusting the code as suggested for the other line to xdot(I+1)=xdot(I)+xddot(I)*dt;
After making this change, Matlab gets stuck, I tried letting it run for a few minutes but won't execute. I ended up having to close and reopen the application.
The error In an assignment A(I) = B, the number of elements in B and I must be the same. is something you should understand because it may pop up frequently in Matlab if you are not careful.
In your case, you are trying to assign 1 element value xdot(I+1) with something which has more than 1 element xdot(I)+xddot*dt.
Indeed, if you step through the code line by line and observe your workspace, you will notice that xddot is not a scalar value as intended, but a full blown vector the size of t. This is because in the precedent line where you define xddot:
xddot =-1/m*(c*xdot(I)-c*L*W*cos(W)+m*g-3*B*((d+x-L*W*sin(W*t)).^(-4)-(d-x-L*W*sin(W*t)).^(-4)));
you still have many references to x (full vector) and t (full vector). You have to replace all these references to full vectors to only one index of them, i.e use x(I) and t(I). The line becomes:
xddot =-1/m*(c*xdot(I)-c*L*W*cos(W)+m*g-3*B*((d+x(I)-L*W*sin(W*t(I))).^(-4)-(d-x(I)-L*W*sin(W*t(I))).^(-4)));
With that your code runs just fine. However, it is far from optimized and it runs relatively slow. I have a powerful machine and it still takes a long time to run for me. I suggest you reduce your time step to something more sensible, at least when you are still trying your code. If you really need that kind of precision, first make sure your code runs fine then when it is ready let it run at full precision and go have a coffee while your computer is doing the work.
The snippet below is the loop part of your code with the correct assignment for xddot. I also added a simple progress bar so you can see that your code is doing something.
hw = waitbar(0,'Please wait...') ;
npt = length(t)-1 ;
for I = 1 : npt
xddot =-1/m*(c*xdot(I)-c*L*W*cos(W)+m*g-3*B*((d+x(I)-L*W*sin(W*t(I))).^(-4)-(d-x(I)-L*W*sin(W*t(I))).^(-4)));
xdot(I+1) = xdot(I)+xddot*dt;
x(I+1) = x(I)+xdot(I+1)*dt ;
pcdone = I / npt ;
waitbar(pcdone,hw,[num2str(pcdone*100,'%5.2f') '% done'])
end
close(hw)
I strongly suggest you reduce your time step to dt = 1e-3; until you are satisfied with everything else.
In the final version, you can remove or comment the calls to the waitbar as it slows down things too.

What is a good substitute for matlabFunction?

I wrote a small program in MATLAB to compute the Shapley value
using the multi-linear extension of a TU game. However, I run
into trouble with the Symbolic Math Toolbox of MATLAB. In
the program I have to integrate a set of functions to get the
Shapley value. However, inside a MATLAB program I cannot use
the int() command
Error using sym/subsindex (line 663) Ivalid indexing or function definition. When defining a function, ensure that the body of the function is a SYM object. When indexing, the input must be numeric, logical or ':'.
Error in ShapleyValueML (line 65)shv(jj)=int(dfy,0,1)
as a consequence I have to use integral() instead. In this case, I
need to transcribe the set of expressions into MATLAB function handle
with matlabFunction(). However, on all Linux machines (MATLAB R2014a) on
which I have access this command does not work (see the discussion below).
As a workaround, the MATLAB program returns the set of functions
into the current workspace, there the Shapley value can be computed
using the int() command.
To make the discussion more concrete, let us consider this small
MATLAB program first.
function [shv,F,dfm]=ShapleyValueML(v)
N=length(v);
[~, n]=log2(N);
S=1:N;
int=0:-1:1-n;
mat=(rem(floor(S(:)*pow2(int)),2)==1);
cmat=(rem(floor(S(:)*pow2(int)),2)==0);
x=sym('x',[1 n]);
mx=1-x;
y = sym('y');
vy=ones(1,n)*y;
F=0;
shv=zeros(1,n);
dfm=cell(1,n);
for ss=1:N
pd1=x(mat(ss,:));
pd2=mx(cmat(ss,:));
pd=prod(pd1)*prod(pd2)*v(ss);
F=pd+F;
end
F=expand(F);
for jj=1:n
dF=diff(F,x(jj));
dfy=subs(dF,x,vy);
%% Does not work!! MATLAB bug???
% mf=matlabFunction(dfy);
% shv(jj)=integral(mf,0,1);
%%
%% The best would be to use:
%%
% shv(jj)=int(dfy,0,1)
%% but it cannot be used inside a program.
dfm{jj}=dfy;
end
end
The commented parts are the parts that do not work inside
the program, but are needed to compute the Shapley value
with that program, which is its purpose. I tested this program
up to 12 players, and I was able to successfully calculate the
Shapley value by a two step procedure. Hence, the above program
specifies correctly the considered problem. To get a better
understanding of this two step procedure and of the functionality
of the above program, let us focus on a three person game.
The values of the coalitions are given by the following data array
>> v = [0,0,90,0,100,120,220];
Notice that coalitions are ordered in accordance with their unique
integer representations. The game is defined, we can now evaluate
the multi-linear extension and the set of partial derivatives with
the above program, but not the Shapley value.
>> [shv,F,dfm]=ShapleyValueML(v);
Integration of the set of partial derivatives runs over the diagonal
of the unit-cube, but then we can set the variables from [x1,x2,x3]
to [y,y,y], and integration runs from 0 to 1.
>> for k=1:3, shv(k)=int(dfm{k},0,1);end;
The solution of the integration is the Shapley value given by:
>> shv
shv =
65 75 80
Checking that this is indeed the Shapley value can be accomplished
with a potential function approach implemented in
>> sh_v=ShapleyValue(v)
sh_v =
65 75 80
that ships with my MATLAB Game Theory Toolbox MatTuGames from
http://www.mathworks.com/matlabcentral/fileexchange/35933-mattugames
Instead of integrating with int() one can also use integral(),
but then the contents like
>> dfm{1}
ans =
- 90*y^2 + 190*y
must be rewritten with matlabFunction() into a function handle. As I
have mentioned above this does not work under Linux
(MATLAB R2013a,R2013b,R2014a). To see this let us try to reproduce
the example
>> syms x y
>> r = sqrt(x^2 + y^2);
from the documentation at the URL:
http://www.mathworks.de/de/help/symbolic/generate-matlab-functions.html?searchHighlight=matlabFunction
This should give
ht =
#(x,y)tanh(sqrt(x.^2+y.^2))
but I get
>> ht = matlabFunction(tanh(r))
Cell contents reference from a non-cell array object.
Error in vectorize (line 15)
c = cells{i};
Error in sym/matlabFunction>mup2mat (line 319)
res = vectorize(res(2:end-1)); % remove quotes
Error in sym/matlabFunction>mup2matcell (line 304)
r = mup2mat(c{1});
Error in sym/matlabFunction (line 123)
body = mup2matcell(funs);
Here comes now my question: Exists there an alternative procedure to
get from
>> dfm{1}
ans =
- 90*y^2 + 190*y
a function handle
>> df=#(y) (- 90.*y.^2 + 190.*y)
df =
#(y)(-90.*y.^2+190.*y)
to integrate it by
>> integral(df,0,1)
ans =
65
Or to put it differently. Is there an alternative method available to
change multiplication * to element-wise multiplication .*, and the
power operation ^ to element-wise power.^?
Of course, any suggestions of improvement for the above MATLAB program
are highly appreciated.
I think I know what the problem is; Towards the beginning of ShapleyValueML function, you have a variable named int which shadows the builtin integration function:
...
int=0:-1:1-n; %# <-- problem!
...
shv(jj)=int(dfy,0,1)
...
That explains the error coming from sym/subsindex, you were using a symbolic object as an index into the numeric array int.
Change the variable name to something else, and the commented code runs fine (the symbolic integration)! Simple as that :)

MATLAB not enough input arguments

I keep trying to run this and have no idea what is going wrong. I have it saved as test.m. I click run in the editor and in the matlab command window, it states not enough input arguments. I feel like I am missing something totally obvious, but I cannot spot the issue.
function y = test(A, x)
%This function computes the product of matrix A by vector x row-wise
% define m number of rows here to feed into for loop
[ma,na] = size(A);
[mx,nx] = size(x);
% use if statement to check for proper dimensions
if(na == mx && nx == 1)
y = zeros(ma,1); % initialize y vector
for n = 1:ma
y(n) = A(n,:)*x;
end
else
disp('Dimensions of matrices do not match')
y = [];
end
end
It is a function (not an script) and it needs some input arguments to run (in this case A and x), so you cannot hit the run button and expect it to run.
The first way:
Instead you can use the command windows in MATLAB and enter the command:
A = rand(3,3); % define A here
x = ones(3,1); % define x here
test(A,x) % then run the function with its arguments
remember that A and x should be defined properly.
The second way is:
Also you can hit the little triangle besides the green run button (see the figure below), and it will show you another option, type command to run. And
there you can directly enter the same command test(A,x). After that, each time you just hit enter for this function and it runs this command instead of only the test command without any argument.
The third way:
function y = test(A, x)
%// TESTING CODE:
if nargin==0
A = default_value_for_A;
x = default_value_for_x;
end
... %// rest of the function code
This way allows you to "click the play button" and have your function run with no explicit input arguments. However, be advised that such a method should only be used:
When debugging, so as not to allow users to call the function with no arguments if this is not its intended use case.
If your function is not supposed to behave differently for a different number of inputs. See also function overloading in MATLAB based on number of input arguments.