使用矩阵、加速框架和iOS工作

8

我有两个矩阵:A和B。

  1. 我该如何将它们存储?
  2. 使用Accelerate框架,我该如何计算矩阵A的逆矩阵?
  3. 我要如何求出A*B的积?
  4. 使用Accelerate框架,我该如何转置矩阵A?

感谢您解答我的问题!

Helper file

#import <Foundation/Foundation.h>
#include <Accelerate/Accelerate.h>

@interface Working_with_matrices : NSObject
-(int)invert_matrix:(int) N andWithMatrix:(double*) matrix;
@end

实现文件

#import "Working_with_matrices.h"
#include <Accelerate/Accelerate.h>

@implementation Working_with_matrices
-(int) matrix_invert:(int) N andWithMatrix:(double*)matrix
{    
int error=0;
int *pivot = malloc(N*N*sizeof(int));
double *workspace = malloc(N*sizeof(double));

dgetrf_(&N, &N, matrix, &N, pivot, &error);

if (error != 0) {
    NSLog(@"Error 1");
    return error;
}

dgetri_(&N, matrix, &N, pivot, workspace, &N, &error);

if (error != 0) {
    NSLog(@"Error 2");
    return error;
}

free(pivot);
free(workspace);
return error;
}

从主函数调用我的代码

#import <Foundation/Foundation.h>
#import "Working_with_matrices.h"

int main(int argc, const char * argv[])
{
int N = 3;
double A[9];
Working_with_matrices* wm=[[Working_with_matrices alloc]init];

A[0] = 1; A[1] = 1; A[2] = 7;
A[3] = 1; A[4] = 2; A[5] = 1;
A[6] = 1; A[7] = 1; A[8] = 3;
[wm invert_matrix:N andWithMatrix:A];
//        [ -1.25  -1.0   3.25 ]
// A^-1 = [  0.5    1.0  -1.5  ]
//        [  0.25   0.0  -0.25 ] 
for (int i=0; i<9; i++) 
{
    NSLog(@"%f", A[i]);
}
return 0;
}
1个回答

8

我对使用加速框架还比较新,但我会尽可能回答问题。

  1. The accelerate framework expects the matrices to be passed in as a 1D array. So if you have a 4x4 matrix, the first row would be placed in indexes 0-3 of your array, the second rouw would be placed in indexes 4-7 and so on.
  2. I've never done it but this answer looks like a good starting point. https://dev59.com/EmXWa4cB1Zd3GeqPOpwA#11321499
  3. The method you'll want to use is vDSP_mmul for single precision or vDSP_mmulD for double precision. You might want to look at the documentation for it to get a better unerstanding of how to use it but heres an example to get you started.

    float *matrixA;  //set by you
    float *matrixB;  //set by you
    float *matrixAB; //the matrix that the answer will be stored in
    
    vDSP_mmul( matrixA, 1, matrixB, 1, matrixAB, 1, 4, 4, 4 );
    // the 1s should be left alone in most situations
    // The 4s in order are:
    //     the number of rows in matrix A
    //     the number of columns in matrix B
    //     the number of columns in matrix A and the number of rows in matrix B.
    

1
是的,加速框架可用于iOS。您可以按照以下说明添加它。https://dev59.com/3XA75IYBdhLWcg3wVXav#3377682 - Craig Siemens
通常这个错误意味着你调用 invert_matrix:andWithMatrix: 的对象没有实现该方法。我建议记录一下你调用该方法的对象,看看它是否是正确的类型。除此之外,如果没有看到你的代码,很难说清楚。 - Craig Siemens
请问您是否可以看一下我在这个主题开头的代码(我没有将其发布到评论中)? - mr.M
1
看起来你的头文件中有 invert_matrix,而在你的实现中却有 matrix_invert,它们应该是相同的。你应该会收到编译器关于此的警告。 - Craig Siemens
@CleverError,使用那段代码我得到了以下警告:“不兼容的指针类型,将'float **'传递给类型为'float *'的参数;请移除&”。这是正常现象吗? - dwbrito
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接