Logical Arrays - In an assignment A(I) = B, the number of elements in B and I must be the same

落爺英雄遲暮 提交于 2020-01-24 16:46:13

问题


I have three matrices, A, B and C. When B is larger than A, I want to saturate the value with A. It says that the number of elements in I (which is (B > A)) must be the same as the number of elements in A. I checked below and they are the same.

>> A = [5 5 5; 5 5 5; 5 5 5];
>> B = [2 2 2; 2 2 2; 2 2 2];
>> C(B > A) = A
In an assignment  A(I) = B, the number of elements in B and I must be the same.

>> numel(B > A)

ans =

     9

>> numel(A)

ans =

     9

>> numel(A>B)

ans =

     9

It is also strange that this works.

>> C(B < A) = A

C =

     5     5     5     5     5     5     5     5     5

I just figured it out...

C(B>A) = B(B>A)

C =

 5     5     5     5     5     5     5     5     5

回答1:


The reason why is because B > A is never satisfied, and produces the empty set. This will produce the empty matrix ([]). Every element of B is actually smaller than A. As such, this is equivalent to performing:

C([]) = A;

You are trying to assign A to nowhere in the matrix, and those dimensions don't match. The reason why B < A works is because every value of B is less than A, and so the assignment of A will work here. In general, you need to make sure that the total number of elements you are accessing on the right side of the expression must equal the same number of elements on the left hand side of the expression you want to assign the elements to.

As you have mentioned in your comments, doing:

C(B > A) = B(B > A)

will work. This is equivalent to doing:

C([]) = B([]);

... essentially, you are performing nothing, so this is a safe operation. No values are being accessed in B are being assigned to locations in A.




回答2:


B>A is a logical 3x3 matrix, but C(B>A) is the empty set, and you are assigning a 3x3 matrix to it. Thus the error. Try

C(B>A)=A(B>A);

On the other hand, C(B < A) is C, a 3x3 matrix, so C(B < A) is C, to which you can assign A.



来源:https://stackoverflow.com/questions/24702385/logical-arrays-in-an-assignment-ai-b-the-number-of-elements-in-b-and-i-mu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!