Mangat Rai Modi
Mangat Rai Modi

Reputation: 5706

Type casting a vector in Matlab

version: Matlab 2009a

I am generating a vector of size <1x116286> using randsrc() function. Since I am again adding it to the matrix of same size but of uint8 type, I am doing as follows -

l=typecast(randsrc(1,v(2)),'uint8');

Now, Matlab has changed the returned a vector of elements - [240,63,0] instead of [-1,1], with the size of <1x930288 uint8>. This is expected as double and uint8 has different size, but I want a vector of same size and values after type casting.

PS: I want to subtract or add '1' from all trhe values on a matrix of size <1x116286>. Is there any other neat way to do this?

Upvotes: 1

Views: 1291

Answers (2)

Mangat Rai Modi
Mangat Rai Modi

Reputation: 5706

well instead of forming a vector (-1,1...) and adding it to some vector 'z' , I did something like this.

l =randsrc(1,v(2));
z(l==-1)=z(l==-1)-1;
z(l==1)=z(l==1)+1;

So, I now, don't need to change types.

Upvotes: 0

James Beilby
James Beilby

Reputation: 1481

As I understand the problem, there are a couple of issues with the above:

  • uint8 is an unsigned type so will not support a negative offset;
  • the "typecast" function is used to reinterpret existing data, not to convert it: here you are interpreting each byte of the floating-point output of randsrc(...) as an integer.

Unfortunately I don't have Matlab handy to test, but the following should provide something closer to what you are after:

l = int8( randsrc(1,v(2)) );

Upvotes: 5

Related Questions