简体   繁体   English

创建一个可以返回对角矩阵的 C++ mex 函数

[英]Creating a C++ mex function that can return a diagonal matrix

I need to create a c++ mex function that input a matrix and return it diagonal with each array in its own block.我需要创建一个 c++ mex 函数,该函数输入一个矩阵并返回它与每个数组在其自己的块中的对角线。 Ex.前任。

input_matrix = ([1,2,3;4,5,6;7,8,9])

output_matrix = 1 2 3 0 0 0 0 0 0
                0 0 0 4 5 6 0 0 0
                0 0 0 0 0 0 7 8 9

Can anyone help I am extremely lost at this point.任何人都可以帮助我在这一点上非常迷茫。

I made this example for you, the basic building block is std::vector.我为你做了这个例子,基本的构建块是 std::vector。 A matrix can be modeled as a std::vector of std::vector.矩阵可以建模为 std::vector 的 std::vector。 std::vector is the C++ standard library type for dynamically allocated arrays std::vector 是动态分配数组的 C++ 标准库类型

#include <cassert>
#include <vector>
#include <iostream>

auto create_diagonal_matrix(const std::vector<std::vector<int>>& input)
{
    std::vector<std::vector<int>> matrix;
    assert(input.size() > 0);
    auto row_size = input[0].size();

    std::size_t prefix_size = 0ul;                                  // number of zeros in front of the next row
    std::size_t postfix_size = (input.size() - 1ul) * row_size;    // how many zeros to append at the end of next row;

    for (const auto& row : input)
    {
        assert(row.size() == row_size);                             // runtime validation, all rows must have same length
        std::vector<int> new_row;
    
        // fill prefix_size indices with 0
        for (std::size_t n = 0ul; n < prefix_size; ++n) new_row.push_back(0);

        // fill input row size entries with values from the input
        for (std::size_t n = 0ul; n < row_size; ++n) new_row.push_back(row[n]);

        // then fill postfix_size indices with 0
        for (std::size_t n = 0ul; n < postfix_size; ++n) new_row.push_back(0);

        matrix.push_back(new_row);

        // adjuest the prefix and postfix sizes
        prefix_size += row_size;
        postfix_size -= row_size;
    }

    return matrix;
}

int main()
{
    // use an initializer list to setup the 2D input array
    // I think in your code this should be done through parsing an input string
    // and then build up a std::vector<std::vector<int>> yourself.
    auto matrix = create_diagonal_matrix({ {1,2,3}, {4,5,6}, {7,8,9} });

    // output the generated matrix.
    for (const auto& row : matrix)
    {
        bool comma = false;
        for (const auto& value : row)
        {
            if (comma) std::cout << ", ";
            std::cout << value;
            comma = true;
        }

        std::cout << "\n";
    }
    std::cout << std::endl;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM