Re: NSConfused... matrices and NSData

Okay, I got it. Thanks, folks.

I had seen an example somewhere which, going by Mike's helpful bit of info, must have been in column-major order - so I had things switched around in my head. Actually, when I saw the example it didn't make sense to me, but I just followed it along blindly! Anyway, this straightens things out.

Much appreciated!



On 29-Mar-09, at 9:55 AM, Ken Thomases wrote:

On Mar 29, 2009, at 11:43 AM, James Maxwell wrote:

Sorry for the long post, but I'm trying to wrap my head around NSData, NSMutableData and matrices.
So I made an example to test my (mis)conception of how this all should work.

Here it is:

- (void) matrixTesting
int numRows = 5;
int numCols = 7;
NSMutableData *theMatrix = [NSMutableData dataWithLength:(numRows * numCols * sizeof(float))];
[theMatrix retain];

float *matrix = [theMatrix mutableBytes];

// Set row 3, col 5 to 3.333
matrix[(3 * numRows) + 5] = 3.333;

You want to multiply by numCols, not numRows. You essentially want to skip rows 0, 1, and 2. Each of those rows contains numCols floats, not numRows floats.

// Set row 2, col 4 to 6.666
matrix[(2 * numRows) + 4] = 6.666;

Same here.

int i,j;
for(i=0;i < numRows;i++)
for(j=0;j < numCols;j++)
NSLog(@"Row %i, Col %i = %f", i, j, matrix[i * numRows
+ j]);

And here.

int getRow = 3;

NSRange rowRange = {
getRow * numRows, numCols * sizeof(float)

Here you get it half right, half wrong. The part you get right is knowing that the size of one row is (numCols * sizeof(float)). Now think: what's the size of the 3 preceding rows which y...

ou want to jump past? It's (getRow * numCols * sizeof(float)), which is what you should be using for the location of your range. That is, you have two problems in the above line. You're multiplying getRow by numRows instead of by numCols, and you're failing to multiply by sizeof(float).


float theRow[numCols];
[theMatrix getBytes:theRow range:rowRange];
for(i=0;i < numCols;i++)
NSLog(@"\n Row test --------> Row 3, index %i = %f", i,

[theMatrix release];



Cocoa-dev mailing list (Cocoa-dev@xxxxxxxxxxxxxxx)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)

Help/Unsubscribe/Update your Subscription:

This email sent to maillists@xxxxxxxxx