ios - 使用矩阵,加速框架,iOS

标签 ios frameworks matrix

我有两个矩阵:A 和 B。

  1. 如何存储它们?
  2. 如何使用 Accelerate 框架计算矩阵 A 的逆矩阵?
  3. 如何找到 A*B 的乘积?
  4. 如何使用 Accelerate 框架转置矩阵 A?

感谢您回答我的问题!

辅助文件

#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. 加速框架期望矩阵作为 一维数组。所以如果你有一个 4x4 矩阵,第一行将被放置 在数组的索引 0-3 中,第二个 rouw 将被放置在 索引4-7等等。
  2. 我从来没有这样做过,但这个答案看起来是一个很好的起点。 https://stackoverflow.com/a/11321499/385017
  3. 您要使用的方法是用于单精度的 vDSP_mmul 或用于 double 的 vDSP_mmulD。你可能想看看 documentation以便更好地了解如何使用它,但这里有一个示例可以帮助您入门。

    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.
    

关于ios - 使用矩阵,加速框架,iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11957699/

相关文章:

r - 将矩阵转换为 R 中定义的三个列

ios - swift,如何从 UIImageView 获取当前显示的图像文件名

c# - 如何连接到 Visual Studio 中的数据库

ios - 从同一应用程序中的框架访问 iOS 应用程序中嵌入的静态库

java - Java 填充垂直矩阵

python - 如何从一个 csv 文件读取多个矩阵?

ios - 将文件保存在 iCloud Drive 文档中(用户访问)

ios - 存储应用程序运行时间的值

ios - 无法识别的选择器发送到实例 0x7fc4e9544fc0

javascript - 在 Meteor 中创建传统 Web 应用程序有哪些缺点?