How can we get user inputs from the keyboard in GNU Octave? - octave

Is there a command like 'scanf' in GNU Octave to read the user inputs from the keyboard?

Yes, the function is called input. A simple example:
octave-3.2.4:3> x = input("Enter a number: ")
Enter a number: 25
x = 25
See the documentation for details, like overriding the default parsing behavior.

In GNU Octave, How to get user input line, aka open stdin:
Make a file called: test.m
Put this code in there:
line = fgetl(stdin);
line
Run it like so:
octave test.m
Enter in some words then press Enter
5 abc 7
The program responds:
line = 5 abc 7
Read more about function: fgetl https://www.gnu.org/software/octave/doc/interpreter/Line_002dOriented-Input.html#XREFfgetl

There is scanf function in addition to input function.
For example:
% Get a number
x = scanf("%d", "C");
% Get a vector of size 5
for i=1:5
x(i) = scanf("%d", "C");
end
% Get a matrix
printf("Enter a 3x2 matrix \n ");
for i=1:3
for j=1:2
n(i,j) = scanf("%d", "C");
end
end
disp(n)

Related

Maxima add current loop iteration to filename

I have code similar to the one below, where a function with a parameter depending on the loop iteration is plotted after every iteration. I would like to save the plot with the name trigplot_i.ps where i is the iteration number, but don't know how.
I have tried trigplot_"i".ps but didn't work, and have not been able to find how to cast i to a string either.
I'm a beginner so any help is very welcome.
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10 do
(plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file,"./trigplot_i.ps"],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
code after edits gives an error:
f(x) := sin(x);
g(x) := cos(x);
for i:1 thru 10
do block([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", myfile),
plot2d([i*f(x), i*g(x)], [x,-5,5],[legend,"sin(x)","cos(x)"],
[xlabel,"x"],[ylabel,"y"],
[ps_file, myfile],
[gnuplot_preamble,"set key box spacing 1.3 top right"])
);
error:
"declare: argument must be a symbol; found "./trigplot_1.ps
-- an error.
To debug this try: debugmode(true);"
Looks good. To construct a file name, try this: sconcat("./trigplot_", i, ".ps") or also you can try: printf(false, "./trigplot_~d.ps", i). My advice is to make that a separate step in the loop, and then you can use it in the call to plot2d, e.g.:
for i:1 thru 10
do block ([myfile],
myfile: sconcat("./trigplot_", i, ".ps"),
printf (true, "iteration ~d, myfile = ~a~%", i, myfile),
plot2d (<stuff goes here>, [ps_file, myfile], <more stuff>));
EDIT: Fixed a bug in printf (omitted argument i).

expand log on Octave

I am trying to expand log expression with octave like that:
expand(log(x^2))
to get 2 * log(x)
but that doesn't work
That works with matlab when making:
expand(log(x^2),'IgnoreAnalyticConstraints',true)
but octave doesn't recognise it.
Any idea how to make it with octave?
You need to specify that x is a positive variable first.
pkg load symbolic
x = sym('x', 'positive' );
expand( log( x ^ 2 ) ) % ans = (sym) 2⋅log(x)

Octave - System of differential equations with lsode

here is my problem. I'm trying to solve a system of two differential equations thanks to the two functions below. The part of the code that give me some trouble is the variable "rho". "rho" is a function which values are given from a file and that I tried to put in the the variable rho.
function [xdot]=f2(x,t)
# Parameters of the equations
t=[1:1:35926];
x = dlmread('data_txt.txt');
rho=x(:,4);
beta = 0.68*10^-2;
g = 1.5;
l = 1.6;
# Definition of the system of 2 ODE's :
xdot(1) = ((rho-beta)/g)*x(1) + l*x(2);
xdot(2) = (beta/g)*x(1)-l*x(2);
endfunction
.
# Initial conditions for the two variables :
x0 = [0;1];
# Definition of the time-vector -> (initial time,temporal mesh,final time) :
t = linspace (1, 10, 10000);
# Resolution with the lsode routine :
x = lsode ("f2", x0, t);
# Plot of the two curves :
plot (t,x);
When I run my code, I get the following error:
>> resolution_effective2
error: f2: A(I) = X: X must have the same size as I
error: called from
f2 at line 34 column 9
resolution_effective2 at line 8 column 3
error: lsode: evaluation of user-supplied function failed
error: called from
resolution_effective2 at line 8 column 3
error: lsode: inconsistent sizes for state and derivative vectors
error: called from
resolution_effective2 at line 8 column 3
I know that my error comes from a mismatch of size between some variable but I have been looking for the error for days now and I don't see. Could someone try to give and explain me an effective correction ?
Thank you
The error might come from your function f2. Its first argument x should have the same dimension as x0 since x0 is the initial condition of x.
In your case, whatever you intent to be the first argument of f2 is ignored since in your function you do x = dlmread('data_txt.txt'); this seems to be a mistake.
Then, xdot(1) = ((rho-beta)/g)*x(1) + l*x(2); will be a problem since rho is a vector.
You need to check the dimensions of x and rho.

Program Works in Python 2.7, but not Python 3.3 (Syntax is compatible for both)

So I have the function integral(function, n=1000, start=0, stop=100) defined in nums.py:
def integral(function, n=1000, start=0, stop=100):
"""Returns integral of function from start to stop with 'n' rectangles"""
increment, num, x = float(stop - start) / n, 0, start
while x <= stop:
num += eval(function)
if x >= stop: break
x += increment
return increment * num
However, my teacher (for my Programming class) wants us to create a separate program that gets the input using input() and then returns it. So, I have:
def main():
from nums import integral # imports the function that I made in my own 'nums' module
f, n, a, b = get_input()
result = integral(f, n, a, b)
msg = "\nIntegration of " + f + " is: " + str(result)
print(msg)
def get_input():
f = str(input("Function (in quotes, eg: 'x^2'; use 'x' as the variable): ")).replace('^', '**')
# The above makes it Python-evaluable and also gets the input in one line
n = int(input("Numbers of Rectangles (enter as an integer, eg: 1000): "))
a = int(input("Start-Point (enter as an integer, eg: 0): "))
b = int(input("End-Point (enter as an integer, eg: 100): "))
return f, n, a, b
main()
When run in Python 2.7, it works fine:
>>>
Function (in quotes, eg: 'x^2'; use 'x' as the variable): 'x**2'
Numbers of Rectangles (enter as an integer, eg: 1000): 1000
Start-Point (enter as an integer, eg: 0): 0
End-Point (enter as an integer, eg: 100): 100
Integration of x**2 is: 333833.5
However, in Python 3.3 (which my teacher insists we use), it raises an error in my integral function, with the same exact input:
Traceback (most recent call last):
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 20, in <module>
main()
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 8, in main
result = integral(f, n, a, b)
File "D:\my_stuff\Google Drive\Modules\nums.py", line 142, in integral
num += eval(function)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
In addition, integral by itself (in Python 3.3) works fine:
>>> from nums import integral
>>> integral('x**2')
333833.4999999991
Because of that, I believe the fault is in my program for my class... Any and all help is appreciated. Thanks :)
The issue you're running into is that input works differently in Python 2 and Python 3. In Python 3, the input function works like the raw_input does in Python 2. Python 2's input function is equivalent to eval(input()) in Python 3.
You're getting into trouble because of the quoteation marks you're typing with the formula. When you type 'x**2' (with the quotes) as your formula when running on Python 2, the text gets evaled in the input function and you get a string with no quotation marks as the result. This works.
When you give the same string to Python 3's input function, it doesn't do an eval, so the quotation marks remain. When you later eval the formula as part of your integral calculation, you get the string x**2 (without any quotation marks) as the result, not the value of x squared. This results in an exception when you try the string to 0.
To fix this, I suggest either using just one version of Python, or putting the following code at the top of your file to get a Python 3 style input in both versions:
# ensure we have Python 3 semantics from input, even in Python 2
try:
input = raw_input
except NameError:
pass
Then just type in your formula without quotation marks and it should work correctly.

How this Erlang function to do BSL on binaries work?

Can someone dumb it down and explain, how this code fragment from a previous answer here works ?
bbsl(Bin,Shift) -> <<_:Shift,Rest/bits>> = Bin, <<Rest/bits,0:Shift>>.
bbsl(Bin, Shift) -> % function accepts binary and number
<< _:Shift, % match Shift number of bits into dummy variable _ and
Rest/bits>> = Bin, % puts rest of the bits into Rest variable from Bin variable
<< Rest/bits, % start creating new binary with bits from Rest at beginning
0:Shift >>. % and Shift number of 0's in the end
hope that made sense