我有以下代码,在Octave中运行良好:
matrizJugadas = [
'1' '2' '3' ;
'4' '5' '6' ;
'7' '8' '9' ;
'10' '11' '12'
];
但是,当我在MATLAB中运行相同的代码时,会抛出以下错误:
The expression on this line will generate an error when executed. The error will be: Error using ==> vertcat
CAT arguments dimensions are not consistent.
??? Error using ==> encuentraPares at 15
Error using ==> vertcat
CAT arguments dimensions are not
consistent.
为什么这在MATLAB中不起作用?
在Octave中,字符数组在长度不同时会自动填充空字符值。例如:
matrizJugadas = [
'1' '2' '3' ;
'4' '5' '6' ;
'7' '8' '9' ;
'10' '11' '12'
]
matrizJugadas =
123
456
789
101112
int32(matrizJugadas )
ans =
49 50 51 32 32 32
52 53 54 32 32 32
55 56 57 32 32 32
49 48 49 49 49 50
注意前三行末尾的额外'空白'字符char(32)
。
无论是否如上所述创建为多行输入,它都将执行此操作:
a = ["1","2","3"; "4","5","6","7"]
a =
123
4567
int32(a)
ans =
49 50 51 32
52 53 54 55
如果您尝试在Matlab中做同样的事情,您将得到您描述的错误:
>> matrizJugadas = [
'1' '2' '3' ;
'4' '5' '6' ;
'7' '8' '9' ;
'10' '11' '12'
];
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
>> a = ["1","2","3"; "4","5","6","7"]
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
这是两个程序之间已知的、故意的不兼容。见https://docs.octave.org/v8.2.0/Character-Arrays.html
对你来说最好的解决方法将取决于你的数据来自哪里以及你想用它做什么。
这是6个元素的宽度:
[ '10' '11' '12' ]
等于
'101112'
和
[ '1' '0' '1' '1' '1' '2' ]
但是这只有3个元素宽:
[ '1' '2' '3' ]
在matlab中,来自R2017x的单引号和双引号的行为有点不同。对于大多数用法,它们是等价的,但对于串联来说不是。单引号定义char数组,双引号定义string。
你的代码试图做的是将每一行连接到一个矩阵中,这意味着它们必须具有相同的维度。正如前面的回答所指出的,第一行连接了['1','2','3']->['123']的维度是1x3,而第三个维度是['10' '11' '12']->['101112']是1x6。然后它尝试垂直它们,但由于尺寸不匹配,它不起作用。
使用双引号,你将定义字符串,不会被连接。
matrizJugadas = ["1" "2" "3" ; "4" "5" "6" ; "7" "8" "9" ; "10" "11" "12"];
通过使用string,虽然你必须检查后面代码的用法,因为它们的行为有点不同。如果你需要它们作为字符,你可以这样做:
matrizJugadas = convertStringsToChars["1" "2" "3" ; "4" "5" "6" ; "7" "8" "9" ; "10" "11" "12"];
这将输出一个带有字符的单元格数组,单元格数组的行为仍然有点不同,您应该重新检查后面的代码。