根据输入i,j从3x3提取次要矩阵 [英] Extract the minor matrix from a 3x3 based on input i,j

查看:202
本文介绍了根据输入i,j从3x3提取次要矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的3x3矩阵,例如: A = [3 1 -4; 2 5 6; 1 4 8]

For a given 3x3 matrix, for example: A = [3 1 -4 ; 2 5 6 ; 1 4 8]

如果我需要用于输入的次要矩阵(1,2) 次要= [2 6; 1 8]

If I need the minor matrix for entry (1,2) Minor = [2 6 ; 1 8]

我已经编写了一个程序来从文本文件中读取矩阵,并且我应该编写一个子程序以根据用户对i,j的输入从主矩阵A中提取次要矩阵.我对Fortran还是很陌生,不知道该怎么做.我做了一些非常绝望的尝试,但是我敢肯定有一种更干净的方法可以做到这一点.

I already wrote a program to read in the matrix from a text file, and I am supposed to write a subroutine to extract the minor matrix from the main matrix A based on the user inputs for i,j. I am very new to Fortran and have no clue how to do that. I made some very desperate attempts but I am sure there is a cleaner way to do that.

我非常拼命,我为i和j的每个可能组合写了9 if函数,但这显然不是明智的选择.感谢您的帮助!

I got so desperate I wrote 9 if functions for each possible combination of i and j but that clearly is not a smart way for doing this. Any help is appreciated!

推荐答案

一种实现此目的的方法是,如@HighPerformanceMark在评论中所述,带有向量下标.您可以声明一个数组,其中包含要保留的行,列也要保留,并将它们作为索引传递给矩阵.像这样:

One way to do this is, as @HighPerformanceMark said in the comment, with vector subscripts. You can declare an array with the rows you want to keep, and the same for columns, and pass them as indices to your matrix. Like this:

function minor(matrix, i, j)
  integer, intent(in) :: matrix(:,:), i, j
  integer :: minor(size(matrix, 1) - 1, size(matrix, 2) - 1)
  integer :: rows(size(matrix, 1) - 1), cols(size(matrix, 2) - 1), k

  rows = [(k, k = 1, i - 1), (k, k = i + 1, size(rows))]
  cols = [(k, k = 1, j - 1), (k, k = j + 1, size(cols))]
  minor = matrix(rows, cols)
end

(我尚未测试,所以请告诉我是否有错误)

(I didn't test it yet, so tell me if there is any error)

另一种选择是根据4个分配构造一个新矩阵,每个分配一个结果(受排除的行/列限制).

Another option would be constructing a new matrix from 4 assignments, one for each quadrant of the result (limited by the excluded row/column).

我更喜欢第一个选项,因为它具有更高的可扩展性.通过将数组作为参数传递,您可以轻松地扩展该函数以删除多个行/列,也可以使其适应更高的尺寸.

I like the first option more because it is more scalable. You could easily extend the function to remove multiple rows/columns by passing arrays as arguments, or adapt it to work on higher dimensions.

这篇关于根据输入i,j从3x3提取次要矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆