How does one have arrays in a Matlab share the same memory
Show older comments
Greetings, Is there a simple means in Matlab for two arrays to share the same data space? In other words letting A be a N by M array of type int32 and B being a NxMX4 type int8. In C I would do this with pointers. Thank you
Accepted Answer
More Answers (3)
Philip Borghesani
on 7 Jul 2016
A libpointer can be (mis)used to do this but I am not sure it will help in the long run due to the overall performance of and copying out (accessing ptr.value) needed with libpointers.
pi8=libpointer('int8Ptr',1:16)
pi16=libpointer('voidPtr',pi8)
pi16.setdatatype('int16Ptr',1,8)
pi16.value(3)=100;
pi8.value
ans =
1×16 int8 row vector
1 2 3 4 100 0 7 8 9 10 11 12 13 14 15 16
1 Comment
Patrick Ford
on 9 Jul 2016
Patrick Ford
on 13 Jul 2016
0 votes
1 Comment
James Tursa
on 15 Jul 2016
Edited: James Tursa
on 15 Jul 2016
In your libpointer example, the value that libpointer creates is a deep data copy of "a". There would be no way to use this libpointer, even in a mex routine, to alter any values in "a". E.g.,
>> a = zeros(1,5)
a =
Structure address = 72ca8b0
m = 1
n = 5
pr = 24545770
pi = 0
0 0 0 0 0
>> px = libpointer('voidPtr', a)
px =
libpointer
>> px.value
ans =
Structure address = 72ca178
m = 1
n = 5
pr = 206aee80
pi = 0
0 0 0 0 0
You can see that the pr data pointers for a and px.value are different, which means that they are not shared data copies of each other.
To have variables of different classes sharing memory and being able to alter one without automatic unsharing, see my mex comment above. You would probably need to employ something like my typecastx FEX submission to accomplish it. Or maybe just pass in the int16 or int32 and manipulate the data elements in-place in the mex routine as int8 without ever creating a shared int8 version of the variable.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!