简体   繁体   English

矩阵尺寸必须一致但实际上相同

[英]Matrix dimensions must agree error while actually the same

I got an error message saying: 我收到一条错误消息:

Matrix dimensions must agree.

Error in tankGame>exmRange (line 119)
    if (p1.dir == 'down') p1.value = imrotate(p1.oriValue, 180,'bilinear'); end

Yet I checked the size of p1.value and p1.oriValue , both of them are 32x32x3 . 但是我检查了p1.valuep1.oriValue的大小,它们都是32x32x3 And if I delete this part the program runs perfectly. 如果我删除了这部分,程序将运行完美。

I assume it's because imrotate somehow changed the dimension (although it shouldn't, for 180-degree square image rotation), so how can I fix it? 我认为这是因为imrotate以某种方式更改尺寸(尽管对于180度的正方形图像旋转,它不应更改),那么如何解决呢?

What is likely generating the error is p1.dir == 'down' . 可能产生错误的是p1.dir == 'down' The == operator is an element-wise operator, it compares each of the characters in the two char vectors, yielding a boolean vector indicating which of the character pairs are equal. ==运算符是元素运算符,它比较两个char向量中的每个字符,产生一个布尔向量,该布尔向量指示哪些字符对相等。 It is not doing a string comparison. 它没有进行字符串比较。

For example, if p1.dir is the char vector 'up ', then you are comparing a vector with 2 characters to one with 4 characters: 例如,如果p1.dir是char向量'up ',那么您正在将一个2个字符的向量与一个4个字符的向量进行比较:

'up'=='down'   % generates the error message "Matrix dimensions must agree."
'doom'=='down' % returns the logical array [true true false false]

Use strcmp to compare strings: 使用strcmp比较字符串:

if strcmp(p1.dir,'down')
   p1.value = imrotate(p1.oriValue, 180,'bilinear');
end

In newer versions of MATLAB (starting with R2016b) there is an actual string type (as opposed to the char vector that has always been called "string" in MATLAB). 在较新版本的MATLAB中(从R2016b开始),存在实际的string类型(与在MATLAB中始终称为“字符串”的char向量相反)。 A string is created with double-quotes: "down" (as opposed to 'down' , which is a char vector). 使用双引号创建一个string"down" (与char载体'down'相反)。 For this new type, the == operator does do a string comparison. 对于这种新类型, ==运算符会进行字符串比较。 When applying the operator to a string an a char vector, the char is converted to a string . 将运算符应用于char向量的stringchar转换为string So another solution would be to do this: 因此,另一种解决方案是:

if p1.dir == "down"
   p1.value = imrotate(p1.oriValue, 180,'bilinear');
end

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

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