将Matlab矩阵输入形式转换为C ++矩阵

时间:2017-11-20 01:59:06

标签: c++ arrays matlab loops matrix

用户将矩阵定义为 Matlab 的方式如下:

>> matrix = [1 2 3;4 5 6;7 8 9;10 11 12]

相当于this

我的目标是将上面的语法转换为规范的C ++矩阵。

我解决这个问题的方法是将字符串(matlab形式的矩阵)作为输入,将其转换为char数组,然后剥离空格和括号,同时将不用空格分隔的数字放在一起。换句话说,像this这样的东西。然而,这一步是我发现很多困难的地方。

我的代码:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

int main()
{

string imatrix;
int n = 0;

cout<<"Matrix: ";
getline(cin,imatrix);

const int dim = imatrix.length();
char im[dim];

for(int i=0; i<dim; i++)
    im[i]=imatrix.at(i);

int rows = 1;
int col = 0;

for(int j=0; j<dim; j++)
{
    if(im[j] == ';')
        rows += 1;
    if(im[j] != '[' && im[j] != ' ' && rows == 1 )
        col += 1;
}

int matrix[rows][col];
int strip[rows*col];
int temp;

/*
This is the part were I am stuck. I need to somehow create the strip 
array.

I tried this:

for(int m = 0; m<dim; i++)
{
    if(im[m]=='[' || im[m] == ' ' || im[m] == ';')
        continue;
    else 
    {
       temp = im[m]; //temporarily save the digit just found 

        //Checking if there are numbers on positions after the one found
        for(int t = m; t<dim, t++)
        {
            if(im[t]!='[' && im[m] != ' ' || im[t] != ';')
            {
                //Somehow save the digits found

            }
            else
            {
                //Somehow save temp followed by the digits found, into position (i) in the array strip. 


                index = t;
                break;
            }
        }

    }
 //Somehow make the loop begin from index
}


*/


for(int k=0; k<rows; k++)
{
    for(int s=0; s<col; s++)
    {

        matrix[k][s] = strip[n];
        n += 1;
    }
}

system("PAUSE");
}

我想补充说我是初学者,我试图用'beginner-methods'来解决这个问题。

附录:

如果您查看上面的代码,评论的部分就是我遇到问题的部分。换句话说,创建'strip array'。

1 个答案:

答案 0 :(得分:0)

首先,在维度解析部分,有一个轻微的错误,它为每个数字增加一列,所以如果你的矩阵在第一行有多个数字条目,它可能会出错。

从数字处理部分开始,由于从左到右读取数字,因此可以使用

temp=temp*10+(im[i]-'0');

你的解析字符是空格或;所以当我读取它时,我会把它们前面读过的数字保存到空间中,就像这样。

strip_idx=0;
if(im[m] == ' ' || im[m] == ';')
{
   strip[strip_idx]=temp;
   strip_idx++;
}

请注意,即使在这些之后,代码仍然非常容易出现输入错误,例如在数字之间有2个空格等。

相关问题