从 2D NSArray 创建 C 数组

发布于 2024-11-15 08:33:42 字数 528 浏览 3 评论 0原文

我有一个 2D NSArray 字符串数字,我想将其转换为 2D C 双精度数组,以便与 BLAS/LAPACK 函数一起使用(通过加速框架)。 这行代码似乎可以工作,但是效率似乎非常低,并且最终由于 malloc 错误而崩溃。有没有更有效的方法将此 2D NSArray 转换为 C 数组?或者将 NSArrays 与 BLAS/LAPACK 一起使用的便捷方法?

double gridDataC[[nrows intValue]+1][[ncol intValue]+1];

for(i=6;i<[fileLines count]-1;i++){
    for(j=0;j<[ncol intValue]-1;j++){
        gridDataC[i][j]=[[[[fileLines objectAtIndex:i] componentsSeparatedByString:@" "] objectAtIndex:j] doubleValue];
    }  
} 

fileLines 是一个数组,其中包含被解析为相应数字的文件行。

I have a 2D NSArray of string numbers that I would like to convert to a 2D C array of doubles for use with BLAS/LAPACK functions (through the accelerate framework).
This line of code seems to work, however seems to be incredibly inefficient and eventually crashes due to a malloc error. Is there a more efficient way to convert this 2D NSArray to a C array? Or a convienent way of using NSArrays with BLAS/LAPACK?

double gridDataC[[nrows intValue]+1][[ncol intValue]+1];

for(i=6;i<[fileLines count]-1;i++){
    for(j=0;j<[ncol intValue]-1;j++){
        gridDataC[i][j]=[[[[fileLines objectAtIndex:i] componentsSeparatedByString:@" "] objectAtIndex:j] doubleValue];
    }  
} 

fileLines is an array that contains lines of a file that are parsed into respective numbers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

要走干脆点 2024-11-22 08:33:42

这里涉及内存的东西很少。

1.componentsSeparatedByString:创建一个自动释放的数组。由于您正在循环查找该字符串中的每个对象,因此您将多次创建类似的数组。由于自动释放的对象直到运行循环结束才被释放,这可能会堵塞内存。最好通过将方法调用移出内循环来执行此操作一次。

2.i的值是最容易混淆的。您将 i 作为 gridDataC 的索引传递。如果您从 i = 6 开始,它可能应该是 i - 6

double gridDataC[[nrows intValue] + 1][[ncol intValue] + 1];

for( i = 6; i < [fileLines count] - 1; i++ ){
    NSArray * components = [[fileLines objectAtIndex:i] componentsSeparatedByString:@" "];
    for( j = 0; j < [ncol intValue] - 1; j++ ){
        gridDataC[i - 6][j] = [[components objectAtIndex:j] doubleValue];
    }  
} 

There are few things here that deal with memory.

1.componentsSeparatedByString: creates an autoreleased array. Since you're looping for every object within that string, you are creating similar array multiple times. As the autoreleased objects are not released until the end of the runloop this might clog the memory. It's better to do this once by bringing the method call out of the inner loop.

2.The value of i is the most confusing. You pass i as the index for gridDataC. It should probably be i - 6 if you're starting from i = 6.

double gridDataC[[nrows intValue] + 1][[ncol intValue] + 1];

for( i = 6; i < [fileLines count] - 1; i++ ){
    NSArray * components = [[fileLines objectAtIndex:i] componentsSeparatedByString:@" "];
    for( j = 0; j < [ncol intValue] - 1; j++ ){
        gridDataC[i - 6][j] = [[components objectAtIndex:j] doubleValue];
    }  
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文