MATIO read complex data - c++

Im trying to convert a program from C++/MEX to just C++ using MATIO and I am wondering if MATIO has an equivalent to mxGetPr(cal) and mxGetPi(cal)? I see in the struct typedef struct matvar_t it has void *data filed
Here is how to write a complex double into a file:
char* fieldname = "MyComplexDoubleVariable";
double real = 4.2;
double imag = 1.5;
mat_complex_split_t mycomplexdouble = {&real, &imag};
size_t dim[2]={ 1, 1 };
matvar_t *variable = Mat_VarCreate(fieldname, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dim, &mycomplexdouble, MAT_F_COMPLEX);
Mat_VarWrite(matfp,variable, MAT_COMPRESSION_NONE); //or MAT_COMPRESSION_ZLIB
Mat_VarFree(variable);
So working backwards I would think this would work
mat_complex_split_t cal_complex=cal->data; but I get this error when compiling
error: conversion from ‘void*’ to non-scalar type ‘mat_complex_split_t’ requested
mat_complex_split_t cal_complex=cal->data;
Any help would be greatly appreciated.

Here is my code to read complex data from mat-file.
I think you should use static_cast to convert void * to specify type.
const mat_complex_split_t* xData = static_cast<const mat_complex_split_t*>(matVar->data);
const double* real = static_cast<const double*>(xData->Re);
const double* imag = static_cast<const double*>(xData->Im);
// Read 10 complex num
for (int i = 0; i < 10; ++i) {
std::cout << real[i] << "+ 1j*"<< imag[i] << std::endl;
}

Related

Is there a reason why VectorLength returns size_t while Vector::size returns uoffset_t?

This sometimes causes problems with 64-Bit compilation. If there is no special reason, I think it would be better to have a consistent index type for VectorLength() and Vector::size().
In this example the call to print_first_n_of_inventory with VectorLength requires a cast.
#include <flatbuffers/flatbuffers.h>
#include <tests/monster_test_generated.h>
#include <iostream>
using namespace flatbuffers;
using namespace MyGame::Example;
void print_first_n_of_inventory(const Vector<uint8_t> * pInventory, uoffset_t n)
{
for (uoffset_t i = 0; i < n; ++i)
{
auto val = pInventory->Get(i);
std::cout << val << "\n";
}
}
int main(int, char * argv[])
{
auto * pMonster = GetMonster(argv[1]);
auto * pInventory = pMonster->inventory();
print_first_n_of_inventory(pInventory, 2);
print_first_n_of_inventory(pInventory, pInventory->size());
// warning C4267: 'argument': conversion from 'size_t' to 'flatbuffers::uoffset_t', possible loss of data
print_first_n_of_inventory(pInventory, VectorLength(pInventory));
return 0;
}
Yes, that is unfortunate, but uoffset_t is the native type of how the length is stored in FlatBuffers, which is always 32-bit. It seemed best to expose this native type than to convert to size_t for the user, as that would cause double conversion in the case where 32-bits would actually be desirable.

I keep getting the error "cannot convert 'float*' to 'float' in return"

I am new to c++ and I'm using the Arduino platform. I was writing a program for my project and at one point I need to convert cartesian coordinate system to cylindrical coordinate system. The program takes in a float array of size 3 and does some stuff to it and returns a new float array of size 3 with the coordinates in the other system. I keep getting the error "exit status 1, cannot convert 'float*' to 'float' in return" and I have absolutely no idea what's wrong with my code or how to fix it. can somebody please help me understand whats going on?
float CartesianToCylindrical (float pos[]){ //pos is in the form of [x,y,z]//
float cylpos[3];
cylpos[0] = sqrt((pos[0] ^ 2) + (pos[1] ^ 2));
cylpos[1] = atan(pos[1] / pos[0]);
cylpos[2] = pos[2];
return cylpos; //return in the form of [r,theta,z]//
Unfortunately, C-style arrays aren't first-class objects in C++, which means you can't easily return them from a function the same way you would other object types. There are ways around that limitation, but they are awkward; the best approach for C++ is to define an object-type instead, like this:
#include <math.h>
#include <array>
#include <iostream>
// Let's define "Point3D" to be an array of 3 floating-point values
typedef std::array<float, 3> Point3D;
Point3D CartesianToCylindrical (const Point3D & pos)
{
//pos is in the form of [x,y,z]//
Point3D cylpos;
cylpos[0] = sqrt((pos[0] * pos[0]) + (pos[1] * pos[1]));
cylpos[1] = atan(pos[1] / pos[0]);
cylpos[2] = pos[2];
return cylpos;
}
int main(int, char **)
{
const Point3D p = {1,2,3};
const Point3D cp = CartesianToCylindrical(p);
std::cout << "(x,y,z) = " << cp[0] << ", " << cp[1] << ", " << cp[2] << std::endl;
}
.... that way you can pass and return your point-values in a natural manner.

C++ got wrong value from array of struct

The problem is as described above. When I try to read values from loaded *.so file (using libdl), whih are in struct I am getting wrong values
Code of application:
#include <dlfcn.h>
#include <iostream>
/* For face data type reproduction */
#define GET_FACE_XYZ_SIZE 1
/* For face_array reproduction */
#define GET_FACE_ARRAY_SIZE 2
#define GET_OBJECT_DATA 3
typedef struct face {
float x[1000];
float y[1000];
float z[1000];
int vertices;
} face;
int main()
{
void *hook;
int (*fn)(int request_type, void *ptr);
hook = dlopen("/root/osms/dlopen-test/lib.so", RTLD_LAZY);
if(!hook)
{
std::cout << "Couldn't find lib.so" << std::endl;
}
fn = dlsym(hook, "object_info");
int face_array_size = fn(GET_FACE_ARRAY_SIZE, NULL);
std::cout << "FACE_ARRAY_SIZE: " << face_array_size << std::endl;
face pointer[face_array_size];
fn(NULL, pointer);
dlclose(hook);
std::cout << "pointer[0].z[1]: " << pointer[0].z[1] << std::endl;
return 0;
}
and code of lib.so:
/* For face data type reproduction */
#define GET_FACE_XYZ_SIZE 1
/* For face array reproduction */
#define GET_FACE_ARRAY_SIZE 2
#define GET_OBJECT_DATA 3
typedef struct face {
float x[1000];
float y[1000];
float z[1000];
int vertices;
} face;
extern "C" int object_info(int request, void *ptr)
{
face face_array[2];
face_array[0].x[0] = 1.1;
face_array[0].y[0] = 0.5;
face_array[0].z[0] = 1.2;
face_array[0].x[1] = 1.6;
face_array[0].y[1] = -0.11;
face_array[0].z[1] = -12;
face_array[0].x[2] = -0.12;
face_array[0].y[2] = 0.24;
face_array[0].z[2] = -0.12;
face_array[0].vertices = 3;
face_array[1].x[0] = -1.1;
face_array[1].y[0] = 0.15;
face_array[1].z[0] = -1.2;
face_array[1].x[1] = -1.6;
face_array[1].y[1] = 0.11;
face_array[1].z[1] = 1.2;
face_array[1].x[2] = 0.12;
face_array[1].y[2] = -0.24;
face_array[1].z[2] = 0.12;
face_array[1].vertices = 3;
if(request == GET_FACE_ARRAY_SIZE)
{
return 2;
}
else
{
ptr = face_array;
}
}
The expected output is pointer[0].z[1]: -12 but I am getting pointer[0].z[1]: -0.12. What's wrong in my code ?
Thanks in advance
Accessing
pointer[0].z[1]
Has undefined behaviour, because it has an indeterminate value.
object_info never modifies the array pointed by ptr. It simply modifies a local array, and assigns the local ptr to point to that local array.
A solution: Don't declare a local array, and instead modify the array pointed by the argument. In other words, repace face face_array[2]; with:
face* face_array = (face*)ptr;
And get rid of the ptr = face_array; that does nothing meaningful.
object_info is declared to return int, but not all code paths return a value. When the function reaches the end of object_info without a return statement, the behaviour is undefined.
A solution: Always return a value if the function is not void.
face_array_size is not a compile time constant value, so face pointer[face_array_size]; will declare a variable length array. VLA are not allowed in C++.
Either use C (VLA are supported since C99, but only optionally supported since C11) instead or use a dynamic array: std::vector<face> or make peace with the fact that your program is not standard compliant.
The variable "face_array" in function object_info and the variable "pointer" in main are not the same variable.
The statement "ptr = face_array" does not change the content of "pointer".
extern "C" int object_info(int request, face *face_array)
{
if(request == GET_FACE_ARRAY_SIZE)
return 2;
face_array[0].x[0] = 1.1;
face_array[0].y[0] = 0.5;
face_array[0].z[0] = 1.2;
face_array[0].x[1] = 1.6;
face_array[0].y[1] = -0.11;
face_array[0].z[1] = -12;
face_array[0].x[2] = -0.12;
face_array[0].y[2] = 0.24;
face_array[0].z[2] = -0.12;
face_array[0].vertices = 3;
face_array[1].x[0] = -1.1;
face_array[1].y[0] = 0.15;
face_array[1].z[0] = -1.2;
face_array[1].x[1] = -1.6;
face_array[1].y[1] = 0.11;
face_array[1].z[1] = 1.2;
face_array[1].x[2] = 0.12;
face_array[1].y[2] = -0.24;
face_array[1].z[2] = 0.12;
face_array[1].vertices = 3;
}

Overloading c++ operators int/float(..)

I'm working on operators in C++ now, but i have one problem. Well I'm trying to overloard int/float operators, I have 2 variables in class
class Zespolona{
public:
float re;
float im;
}
I've done all of my operators but when i do
operator int const(){
this->re = (int)this->re;
this->im = (int)this->im;
return *this;
}
then it gets an infinite loop.
My main
int main(){
Zespolona z1;
z1.re = 1.2;
z1.im = 34.9;
z1 = (int)z1;
cout << z1 << endl;
}
What can i do, to get int of two of those variables?
I am not completely sure what you are trying to achieve. I am guessing one of the following two possibilities:
1) Covert the two floats of your class (re, im) into integers:
This is rather simple. Since the two members are public you can access them directly:
#include <iostream>
int main()
{
Zespolona Z1;
Z1.re = 1.2;
Z1.im = 34.9;
std::cout << "Re: " << (int) Z1.re << std::endl;
std::cout << "Im: " << (int) Z1.im << std::endl;
return 0;
}
The output of this program should be:
Re: 1
Im: 34
Note: When you convert a float to an integer everything after the decimal dot is omitted (at least that is the behavior using g++ under Ubuntu).
If you want the two floats to be private or protected you would have to create methods like int GetRe() and int GetIm().
2) Convert the two floats of your class (re, im) into one integer using the integer conversion operator operator int const(). This operator has to return exactly one int. For the following example I decided to return the absolute value (magnitude) of the complex number (since your members are called re and im I am guessing the class is used for complex numbers):
class Zespolona
{
public:
float re;
float im;
operator int const()
{
return (int) sqrt(re*re + im*im);
}
};
int main()
{
Zespolona Z1;
Z1.re = 1.2;
Z1.im = 34.9;
std::cout << "Z1: " << (int) Z1 << std::endl;
return 0;
}
The output should now be:
Z1: 34
Note: Again the correct (float) result 34.92... is converted into the integer 34.
The code you mentioned in your questions returns a reference to your class Zespolona when you try to convert it into int. Thus, the compiler again tries to convert that reference into an int. But all it gets is again a reference to Zespolona, and so on. Hence, you get an infinite loop.

C/C++ changing the value of a const

I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to replicate it I'm not being able to put it to compile.
The concept was that it is possible to change by accident the value of a const in C/C++
It was something like this:
const int a = 3; // I promise I won't change a
const int *ptr_to_a = &a; // I still promise I won't change a
int *ptr;
ptr = ptr_to_a;
(*ptr) = 5; // I'm a liar; a is now 5
I wanted to show this to a friend but now I'm missing a step. Does anyone know what's missing for it to start compiling and working?
ATM I'm getting invalid conversion from 'const int*' to 'int*' but when I read the article I tried and it worked great.
you need to cast away the constness:
linux ~ $ cat constTest.c
#include <stdio.h>
void modA( int *x )
{
*x = 7;
}
int main( void )
{
const int a = 3; // I promisse i won't change a
int *ptr;
ptr = (int*)( &a );
printf( "A=%d\n", a );
*ptr = 5; // I'm a liar, a is now 5
printf( "A=%d\n", a );
*((int*)(&a)) = 6;
printf( "A=%d\n", a );
modA( (int*)( &a ));
printf( "A=%d\n", a );
return 0;
}
linux ~ $ gcc constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=5
A=6
A=7
linux ~ $ g++ constTest.c -o constTest
linux ~ $ ./constTest
A=3
A=3
A=3
A=3
also the common answer doesn't work in g++ 4.1.2
linux ~ $ cat constTest2.cpp
#include <iostream>
using namespace std;
int main( void )
{
const int a = 3; // I promisse i won't change a
int *ptr;
ptr = const_cast<int*>( &a );
cout << "A=" << a << endl;
*ptr = 5; // I'm a liar, a is now 5
cout << "A=" << a << endl;
return 0;
}
linux ~ $ g++ constTest2.cpp -o constTest2
linux ~ $ ./constTest2
A=3
A=3
linux ~ $
btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.
Note any attempt to cast away constness is undefined by the standard. From 7.1.5.1 of the standard:
Except that any class member declared
mutable can be modified, any
attempt to modify a const object
during its lifetime
results in undefined behavior.
And right after this example is used:
const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object
So in short what you want to do isn't possible using standard C++.
Further when the compiler encounters a declaration like
const int a = 3; // I promisse i won't change a
it is free to replace any occurance of 'a' with 3 (effectively doing the same thing as #define a 3)
Just a guess, but a common question is why one can't convert an int** to a const int**, which at first appears to be reasonable (after all, you're just adding a const, which is normally ok). The reason is that if you could do this, you could accidentally modify a const object:
const int x = 3;
int *px;
const int **ppx = &px; // ERROR: conversion from 'int**' to 'const int**'
*ppx = &x; // ok, assigning 'const int*' to 'const int*'
*px = 4; // oops, just modified a const object
It's a very non-intuitive result, but the only way to make sure that you can't modify a const object in this case (note how there are no typecasts) is to make line 3 an error.
You're only allowed to add const without a cast at the FIRST level of indirection:
int * const *ppx = &px; // this is ok
*ppx = &x; // but now this is an error because *ppx is 'const'
In C++, it is impossible to modify a const object without using a typecast of some sort. You'll have to use either a C-style cast or a C++-style const_cast to remove the const-ness. Any other attempt to do so will result in a compiler error somewhere.
Back in the mists of time, we paleo-programmers used FORTRAN. FORTRAN passed all its parameters by reference, and didn't do any typechecking. This meant it was quite easy to accidentally change the value of even a literal constant. You could pass "3" to a SUBROUTINE, and it would come back changed, and so every time from then on where your code had a "3", it would actually act like a different value. Let me tell you, those were hard bugs to find and fix.
Did you try this?
ptr = const_cast<int *>(ptr_to_a);
That should help it compile but it's not really by accident due to the cast.
In C++, Using Microsoft Visual Studio-2008
const int a = 3; /* I promisse i won't change a */
int * ptr1 = const_cast<int*> (&a);
*ptr1 = 5; /* I'm a liar, a is now 5 . It's not okay. */
cout << "a = " << a << "\n"; /* prints 3 */
int arr1[a]; /* arr1 is an array of 3 ints */
int temp = 2;
/* or, const volatile int temp = 2; */
const int b = temp + 1; /* I promisse i won't change b */
int * ptr2 = const_cast<int*> (&b);
*ptr2 = 5; /* I'm a liar, b is now 5 . It's okay. */
cout << "b = " << b << "\n"; /* prints 5 */
//int arr2[b]; /* Compilation error */
In C, a const variable can be modified through its pointer; however it is undefined behavior. A const variable can be never used as length in an array declaration.
In C++, if a const variable is initialized with a pure constant expression, then its value cannot be modified through its pointer even after try to modify, otherwise a const variable can be modified through its pointer.
A pure integral const variable can be used as length in an array declaration, if its value is greater than 0.
A pure constant expression consists of the following operands.
A numeric literal (constant ) e.g. 2, 10.53
A symbolic constant defined by #define directive
An Enumeration constant
A pure const variable i.e. a const variable which is itself initialized with a pure constant expression.
Non-const variables or volatile variables are not allowed.
Some of these answers point out that the compiler can optimize away the variable 'a' since it is declared const. If you really want to be able to change the value of a then you need to mark it as volatile
const volatile int a = 3; // I promise i won't change a
int *ptr = (int *)&a;
(*ptr) = 5; // I'm a liar, a is now 5
Of course, declaring something as const volatile should really illustrate just how silly this is.
this will create a runtime fault. Because the int is static. Unhandled exception. Access violation writing location 0x00035834.
void main(void)
{
static const int x = 5;
int *p = (int *)x;
*p = 99; //here it will trigger the fault at run time
}
You probably want to use const_cast:
int *ptr = const_cast<int*>(ptr_to_a);
I'm not 100% certain this will work though, I'm a bit rusty at C/C++ :-)
Some readup for const_cast: http://msdn.microsoft.com/en-us/library/bz6at95h(VS.80).aspx
const int foo = 42;
const int *pfoo = &foo;
const void *t = pfoo;
void *s = &t; // pointer to pointer to int
int **z = (int **)s; // pointer to int
**z = 0;
The article you were looking at might have been talking about the difference between
const int *pciCantChangeTarget;
const int ci = 37;
pciCantChangeTarget = &ci; // works fine
*pciCantChangeTarget = 3; // compile error
and
int nFirst = 1;
int const *cpiCantChangePointerValue = &nFirst;
int nSecond = 968;
*pciCantChangePointerValue = 402; // works
cpiCantChangePointerValue = &ci; // compile error
Or so I recall-- I don't have anything but Java tools here, so can't test :)
#include<iostream>
int main( void )
{
int i = 3;
const int *pi = &i;
int *pj = (int*)&i;
*pj = 4;
getchar();
return 0;
}
I was looking on how to convert between consts and I found this one http://www.possibility.com/Cpp/const.html maybe it can be useful to someone. :)
I have tested the code below and it successfully changes the constant member variables.
#include <iostream>
class A
{
private:
int * pc1; // These must stay on the top of the constant member variables.
int * pc2; // Because, they must be initialized first
int * pc3; // in the constructor initialization list.
public:
A() : c1(0), c2(0), c3(0), v1(0), v2(0), v3(0) {}
A(const A & other)
: pc1 (const_cast<int*>(&other.c1)),
pc2 (const_cast<int*>(&other.c2)),
pc3 (const_cast<int*>(&other.c3)),
c1 (*pc1),
c2 (*pc2),
c3 (*pc3),
v1 (other.v1),
v2 (other.v2),
v3 (other.v3)
{
}
A(int c11, int c22, int c33, int v11, int v22, int v33) : c1(c11), c2(c22), c3(c33), v1(v11), v2(v22), v3(v33)
{
}
const A & operator=(const A & Rhs)
{
pc1 = const_cast<int*>(&c1);
pc2 = const_cast<int*>(&c2),
pc3 = const_cast<int*>(&c3),
*pc1 = *const_cast<int*>(&Rhs.c1);
*pc2 = *const_cast<int*>(&Rhs.c2);
*pc3 = *const_cast<int*>(&Rhs.c3);
v1 = Rhs.v1;
v2 = Rhs.v2;
v3 = Rhs.v3;
return *this;
}
const int c1;
const int c2;
const int c3;
int v1;
int v2;
int v3;
};
std::wostream & operator<<(std::wostream & os, const A & a)
{
os << a.c1 << '\t' << a.c2 << '\t' << a.c3 << '\t' << a.v1 << '\t' << a.v2 << '\t' << a.v3 << std::endl;
return os;
}
int wmain(int argc, wchar_t *argv[], wchar_t *envp[])
{
A ObjA(10, 20, 30, 11, 22, 33);
A ObjB(40, 50, 60, 44, 55, 66);
A ObjC(70, 80, 90, 77, 88, 99);
A ObjD(ObjA);
ObjB = ObjC;
std::wcout << ObjA << ObjB << ObjC << ObjD;
system("pause");
return 0;
}
The console output is:
10 20 30 11 22 33
70 80 90 77 88 99
70 80 90 77 88 99
10 20 30 11 22 33
Press any key to continue . . .
Here, the handicap is, you have to define as many pointers as number of constant member variables you have.
we can change the const variable value by the following code :
const int x=5;
printf("\nValue of x=%d",x);
*(int *)&x=7;
printf("\nNew value of x=%d",x);
#include<stdio.h>
#include<stdlib.h>
int main(void) {
const int a = 1; //a is constant
fprintf(stdout,"%d\n",a);//prints 1
int* a_ptr = &a;
*a_ptr = 4;//memory leak in c(value of a changed)
fprintf(stdout,"%d",a);//prints 4
return 0;
}
Final Solution: it will change const variable a value;
cont int a = 10;
*(int*)&a= 5; // now a prints 5
// works fine.
The step you're missing is that you don't need the int* pointer. The line:
const int *ptr_to_a = &a; // I still promiss i won't change a;
actually says you won't change ptr_to_a, not a. So if you changed your code to read like this:
const int a = 3; // I promise I won't change a
const int *ptr_to_a = &a; // I promise I won't change ptr_to_a, not a.
(*ptr_to_a) = 5; // a is now 5
a is now 5. You can change a through ptr_to_a without any warning.
EDIT:
The above is incorrect. It turns out I was confusing a similar trick with a shared_ptr, in which you can get access to the raw pointer and modify the internal data value without firing off any warnings. That is:
#include <iostream>
#include <boost/shared_ptr.hpp>
int main()
{
const boost::shared_ptr<int>* a = new boost::shared_ptr<int>(new int(3));
*(a->get()) = 5;
std::cout << "A is: " << *(a->get()) << std::endl;
return 0;
}
Will produce 5.