I am programming in C++ and want to use the powerful built-in functions in Octave. I followed the standalone programguideline on Octave website. I can run the function norm (which is called as Fnorm in C++) with the sample code successfully. Now I want to use the function mldivide to solve a linear equation.
#include <iostream>
#include <octave/oct.h>
#include <octave/builtin-defun-decls.h>
octave_value_list input;
octave_value_list retval;
int main (void) {
Matrix A(4,4);
for (octave_idx_type i = 0; i < 4; i++)
for (octave_idx_type j = 0; j < 4; j++)
A(i,j) = 1.0 / (static_cast<double> (i) +static_cast<double> ( j ) + 1.0 ) ;
ColumnVector b(4,1.0);
input.append(A);
input.append(b);
retval=Fmldivide(input);
ColumnVector x =retval(0).column_vector_value();
std::cout << "A = " << std::endl << A << std::endl
<< "b = " << std::endl << b << std::endl
<< "x = " << std::endl << x << std::endl;
return 0;
}
But there are errors as follow.
main.cpp: In function 'int main()':
main.cpp:23:26: error: invalid initialization of reference of type 'const octave_value_list&' from expression of type 'Matrix'
In file included from main.cpp:3:0:
/usr/local/octave/3.8.0/include/octave-3.8.0/octave/../octave/builtin-defun-decls.h:198:1: error: in passing argument 1 of 'octave_value_list Fmldivide(const octave_value_list&, int)'
Any thoughts?
There are two reasons why this is not working:
Fmldivide takes an octave_value_list as input
Fmldivide returns an octave_value_list but you are declaring a ColumnVector
You can fix the first by:
converting your input into a single octave_value and leaving the conversion to octave_value_list to the compiler:
Fmldivide (octave_value (b), 1);
use do_binary_op with the left division operator:
do_binary_op (octave_value::op_ldiv, b, 1);
You can fix the second by using the column_vector_value method:
if you are using Fmldivide you get a list, so you must index the first element first:
ColumnVector x = Fmldivide (b, 1)(0).column_vector_value ();
if you use do_binary_op you will get an octave_value so indexing is unecessary:
ColumnVector x = do_binary_op (octave_value::op_ldiv, b, 1).column_vector_value ();
Related
This question already has answers here:
problem sorting using member function as comparator
(9 answers)
Closed 2 years ago.
I'm trying to implement this code for Linear Regression here but it is unable to compile due to std::sort returning several errors.
#include "LinearRegression.h"
#include <iostream>
#include <algorithm>
#include <vector>
bool LinearRegression::custom_sort(double a, double b) /*sorts based on absolute min value or error*/
{
double a1 = abs(a-0);
double b1 = abs(b-0);
return a1<b1;
}
void LinearRegression::predict()
{
/*Intialization Phase*/
double x[] = { 1, 2, 4, 3, 5 }; //defining x values
double y[] = { 1, 3, 3, 2, 5 }; //defining y values
double err;
double b0 = 0; //initializing b0
double b1 = 0; //initializing b1
double alpha = 0.01; //intializing error rate
std::vector<double>error; // array to store all error values
/*Training Phase*/
for (int i = 0; i < 20; i++) //
{
int idx = i % 5; //for accessing index after every epoch
double p = b0 + b1 * x[idx]; //calculate prediction
err = p - y[idx]; //calculate error
b0 = b0 - alpha * err; //update b0
b1 = b1 - alpha * err * x[idx]; // updating b1
std::cout << "B0=" << b0 << " " << "B1=" << b1 << " " << "error=" << err << std::endl; //print values after every update
error.push_back(err);
}
std::sort(error.begin(),error.end(),custom_sort); //sorting based on error values
std::cout << "Final Values are: " << "B0=" << b0 << " " << "B1=" << b1 << " " << "error=" << error[0] << std::endl;
/*Testing Phase*/
std::cout << "Enter a test x value";
double test;
std::cin >> test;
double pred = b0 + b1 * test;
std::cout << std::endl;
std::cout << "The value predicted by the model= " << pred;
}
I get the errors:
non-standard syntax; use '&' to create a pointer to member
and
no matching overloaded function found
for this line
std::sort(error.begin(),error.end(),custom_sort);
custom_sort is a non-static member function, it can't work with sort directly because under the hood it expects three arguments, not two - the first one is the object pointer.
In your particular example, custom_sort doesn't use any data members, so it can be made static (static should go into the declaration):
static bool LinearRegression::custom_sort(double a, double b);
Then you could write:
std::sort(error.begin(), error.end(), &custom_sort);
Note that you need & to form a pointer to a member function, as the error message suggests. However, for static member function it can be omitted (similar to free functions).
I am relatively new to c++ programming, I have an assignment to code the Newton Raphson method however I have the error error:
called object type 'double' is not a function or function pointer
This error appears when I am trying to compile my code. I tried some basic changes to assign pointer but I probably did it in the wrong way, my code is printed below, can anybody explain how can I overcome this?
#include <iostream>
#include <math.h>
using namespace std;
double f(double x); //this is f(x)
double f(double x) {
double eq1 = exp(x) + pow(x,3) + 5;
return eq1;
}
double f1(double x); //this is the first derivative f'(x)
double f1(double x) {
double eq2 = exp(x) + 3*pow(x,2);
return eq2;
}
int main() {
double x, xn, f, f1, eps;
cout << "Select first root :" << '\n'; //Here we select our first guess
cin >> xn;
cout << "Select Epsilon accuracy :" << '\n';
cin >> epsi;
f = f(x);
f1 = f1(x);
cout << "x_n" << " " << "x_(n+1)" << " " << "|x_(n+1) - x_1|" << '\n';
do {
x = xn; //This is the first iteneration step where x takes the value of the last itenarated (known) root xn
f = f(x);
f1 = f1(x);
xn = x - (f/f1); //this the formula that sets the itenaration going
cout << x << " " << xn << " " << fabs(xn - x) << '\n';
}
while( fabs(xn - x) < epsi ); //If |x_(n+1) - x_n| is smaller than the desired accurcay than the itenaration continues
cout << "The root of the equation is " << xn << '\n';
return 0;
}
Thank you
You have local variables with the same name as the functions, thus
f = f(x);
f1 = f1(x);
cannot work.
Rename either the functions or the variables. Anyhow single letter variable/function names are not nice. Use descriptive names. You (or anybody else) taking a look at the code after some weeks will be thankful for that.
PS: you also dont need the forward declarations. And the functions can be written a bit shorter:
//double f(double x); // this you dont need
double f(double x) {
return exp(x) + pow(x,3) + 5;
}
Also using namespace std; is considered bad practice. In this case it does little to no harm, but you better get rid of this bad habit before it does matter.
Last but not least you should format your code properly. This
while( fabs(xn - x) < epsi );
looks very nasty, because it seems to be an infinite loop. I almost never use the do-while loop, however, I suggest you to write it like this:
do {
// ...
} while ();
because usually whenever you see a while with a ; in the same line you should start to panic ;) (while loops are much more common than do-while and errors caused by a ; after the condition in a while loop can be a pain in the a** to debug)
You are attempting to use functions called f and f1 and doubles called f and f1. If you call the variables or the function something else, then you can resolve the error. It would be good coding practice to give these variables better names that tell the reader what they do and avoid mistakes like this one.
There were several errors in your code. I made it compilable:
#include <iostream>
#include <math.h>
using namespace std;
double func(double x); //this is f(x)
double func(double x) {
double eq1 = exp(x) + pow(x,3) + 5;
return eq1;
}
double func1(double x); //this is the first derivative f'(x)
double func1(double x) {
double eq2 = exp(x) + 3*pow(x,2);
return eq2;
}
int main() {
double x, xn, f, f1, eps;
cout << "Select first root :" << '\n'; //Here we select our first guess
cin >> xn;
cout << "Select Epsilon accuracy :" << '\n';
cin >> eps;
f = func(x);
f1 = func1(x);
cout << "x_n" << " " << "x_(n+1)" << " " << "|x_(n+1) - x_1|" << '\n';
do {
x = xn; //This is the first iteneration step where x takes the value of the last itenarated (known) root xn
f = func(x);
f1 = func1(x);
xn = x - (f/f1); //this the formula that sets the itenaration going
cout << x << " " << xn << " " << fabs(xn - x) << '\n';
}
while( fabs(xn - x) < eps ); //If |x_(n+1) - x_n| is smaller than the desired accurcay than the itenaration continues
cout << "The root of the equation is " << xn << '\n';
return 0;
}
The main problems were:
you defined the variable f with the same name of the f(x) function (the same error was repeated for the f'(x) function) and
you declared the eps variable to represent epsilon in your program but you tried to access to it several times by calling it epsi.
I know this is a similar question to previous questions but I couldn't find a suitable answer that I could follow.
I am trying to create an array of values in a function and then return a pointer to this array to be used in later functions and in the main. I am having issues simply in understanding how to properly send and access the array. Following is a portion of my code (I have deleted irrelevant parts only)
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
double *PMS() {
static double w[128];
double dw = 0.05;
int i;
for (i = 1; i <= M; i++) {
w[i] = dw + (2*i - 1) * (dw/2.0);
cout << w[i] << endl;
}
cout << w[i] << endl;
return w;
}
//======================================================================
void RandSea() {
double *omega;
int i;
omega = PMS();
for (i = 0; i <=129;i++)
cout << *omega << endl;
}
int main() {
data(values);
Pierson_Moskowitz();
RandSeaState();
}
The array is not correctly sending the values 0x6021e0 from cout<<omega<<endl; in the RandSea function.
the value for omega is just zero.
There are many things to note here:-
1) array indices start at 0 and ends at size-1.
2) cout << omega << endl;
This would be printing the base address of the array.
You should use :-
omega = PMS();
for ( int i = 0; i < 129; i++ ) <<<<Here 129 should be the number of elements array has
{
cout << *(omega + i) << endl;
}
3) You are returning the address of array to the caller. How would it get to know how many elements are there in an array.
"My second question is that I'm also having some trouble understanding the difference between the * and the & for pointers"
The & is known as "address of" operator. It used to get an address of an object. And '*' is "value at address of" operator in context of pointers.
**Essentially I was given pseudo code:
"x = 1
repeat 10 times: x = (x + n / x) / 2
return x"
And the pseudo code for the int main function (int main function to print out my n values in the cout) at the end, in order to create a sqrt function program. I get the following errors on linux2 compiler:
: In function ‘double my_sqrt_1(double)’:
:9:1: error: expected primary-expression before ‘return’
:9:1: error: expected ‘;’ before ‘return’
: In function ‘int main()’:
:
15:13: error: expected unqualified-id before ‘-’ token
:~> expected primary-expression before ‘return’
Help is much appreciated!
#include <iostream>
#include <math.h>
using namespace std;
double my_sqrt_1(double n)
{
for (int x= 1; x<10; ++x)
cout<< x << '\t' << x=(x+n/x)/2 <<
return x;
}
int main()
{
int n= 3.141459;
int k= -100,-10,-1,0,1,10,and 100;
for(auto k : { -100,-10,-1,0,1,10,100}){
n=3.14159 * pow (10.0,k);
cout << "print n,sqrt(n),and my_sqrt_1(n)" ;
return 0;
}
}
You missed a semicolon at the end of the cout line:
double my_sqrt_1(double n)
{
for (int x= 1; x<10; ++x)
cout<< x << '\t' << x=(x+n/x)/2;
return x;
}
The clue is in the error:
:9:1: error: expected ‘;’ before ‘return’
Finding the source of compiler errors can be tricky for those new to C/C++, if you miss a semi-colon the line reported will often differ from the one containing the actual error. As in this case where the return line became part of the same statement as the line above.
Also here:
int k= -100,-10,-1,0,1,10,and 100;
That is not how you define an array, you should read up on the basics of those since you're new to the game, which is evident here:
cout << "print n,sqrt(n),and my_sqrt_1(n)" ;
Where you're not calling any functions but instead outputting a static string of text. You need to make the function calls and variable outputs outside of the literal string:
cout << "print " << n << "," << sqrt(n) << ", and" << my_sqrt_1(n);
Trying to add command line arguments to my programs. So I was experimenting and cannot figure out this intellisense warning for the life of me. It keeps on saying it is expecting a ')', but I have no idea why.
Here is the code it does not like:
// Calculate average
average = sum / ( argc – 1 );
Then it underlines the subtraction operator. Below is the full program.
#include <iostream>
int main( int argc, char *argv[] )
{
float average;
int sum = 0;
// Valid number of arguments?
if ( argc > 1 )
{
// Loop through arguments ignoring the first which is
// the name and path of this program
for ( int i = 1; i < argc; i++ )
{
// Convert cString to int
sum += atoi( argv[i] );
}
// Calculate average
average = sum / ( argc – 1 );
std::cout << "\nSum: " << sum << '\n'
<< "Average: " << average << std::endl;
}
else
{
// If invalid number of arguments, display error message
// and usage syntax
std::cout << "Error: No arguments\n"
<< "Syntax: command_line [space delimted numbers]"
<< std::endl;
}
return 0;
}
The character you think is a minus sign is something else, so it is not parsed as a subtraction operator.
Your version:
average = sum / ( argc – 1 );
Correct version (cut and paste into your code):
average = sum / ( argc - 1 );
Note that calculating an average using integers might not be the best way to do it. You have integer arithmetic on the RHS, which you then assign to float on the LHS. You should perform the division using floating point types. Example:
#include <iostream>
int main()
{
std::cout << float((3)/5) << "\n"; // int division to FP: prints 0!
std::cout << float(3)/5 << "\n"; // FP division: prints 0.6
}
I tried to compile your code on my machine with g++ 4.6.3 and got the follow error:
pedro#RovesTwo:~$ g++ teste.cpp -o teste
teste.cpp:20:8: erro: stray ‘\342’ in program
teste.cpp:20:8: erro: stray ‘\200’ in program
teste.cpp:20:8: erro: stray ‘\223’ in program
teste.cpp: Na função ‘int main(int, char**)’:
teste.cpp:16:33: erro: ‘atoi’ was not declared in this scope
teste.cpp:20:35: erro: expected ‘)’ before numeric constant
Looks like there is some strange char in that line. Remove and re-write the line fixed the error.