
本文共 1025 字,大约阅读时间需要 3 分钟。
Objective-C 实现矩阵类 Matrix
#import <Foundation/Foundation.h>
@interface Matrix : NSObject
@property (nonatomic, assign) NSInteger rows; @property (nonatomic, assign) NSInteger cols;
- (id)initWithRows:(NSInteger)rows cols:(NSInteger)cols;
- (id)initWithArray:(NSArray *)array;
- (id)addMatrix:(Matrix *)matrix;
- (id)multiplyMatrix:(Matrix *)matrix;
- (NSString *)toString;
- (void)print;
@end
Matrix 类实现了矩阵的基本操作,支持矩阵的创建、打印、加法和乘法。开发者可以通过以下方式创建矩阵实例:
[Matrix newMatrixWithRows:3 cols:4];
- 使用数组初始化矩阵:
- 矩阵加法:
- 矩阵乘法:
- 打印矩阵:
[Matrix matrixWithArray:[NSArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @10]];
Matrix *matrixA = [Matrix newMatrixWithRows:3 cols:4]; Matrix *matrixB = [Matrix newMatrixWithRows:3 cols:4]; matrixA = [matrixA addMatrix:matrixB]; // 返回新的矩阵结果
Matrix *matrixA = [Matrix newMatrixWithRows:3 cols:4]; Matrix *matrixB = [Matrix newMatrixWithRows:4 cols:3]; matrixA = [matrixA multiplyMatrix:matrixB]; // 返回新的矩阵结果
[matrixA print];
Matrix 类提供了 toString 方法,可以将矩阵转换为字符串格式,便于调试和分析。开发者可以根据需要扩展更多矩阵操作功能,满足复杂应用的需求。
发表评论
最新留言
关于作者
