compare the value of two matrix
2 次查看(过去 30 天)
显示 更早的评论
Hi! I have a problems with this code:
for k=1:5
for i=1:size(A(1,k).a,1)
for j=1:size(dateAll(1,k).date,1)
if(A(1,k).a(i,:)==dateAll(1,k).date(j,1:3))
if(dateAll(1,k).date(:,4)==1)
A(1,k).b(:,1)=s(1,k).places.all(1,i);
end
end
end
end
end
It doesn't generate error but doesn't do what i want! Can you help me?
2 个评论
回答(1 个)
Walter Roberson
2015-11-4
Your code has == between vectors. Code that does that is often wrong and always unclear even if it is not wrong. Please read about all() and any()
2 个评论
Walter Roberson
2015-11-8
The result of an individual comparison is false or true. false is represented by 0 and true is represented by 1. When you compare two vectors or matrices you get a vector or matrix that contains 0 and 1, but it is possible that matrix is not completely 0 (every comparison false) or completely 1 (every comparison true). With that being the case, you have to decide what you want to happen if some of the comparisons come out true (1) but others do not come out true (and so are 0).
Do you want to restrict the overall comparison of the two matrices to be considered true only if all of the results were true? That is what MATLAB does by default, but it is clearer to the reader (and to you) if you specifically code that by wrapping all() around the comparison, as in
if all(A(1,k).a(i,:)==dateAll(1,k).date(j,1:3))
Or do you want the overall comparison to to be considered true if at least one of the individual comparisons is true? If so then you need to code that specially, such as
if any(A(1,k).a(i,:)==dateAll(1,k).date(j,1:3))
Sometimes when people compare vectors, what they want to know is whether the values on one side appear anywhere on the other side, For example if you want to check whether a group of daynumber (of the week) is the code for saturday (7) or sunday (1) then they might ask
if daynumbers == [1 7]
which will fail with an error unless daynumbers happens to contain exactly 1 or exactly 2 elements. What they should be using instead is something more like ismember()
if all( ismember(daynumbers, [1 7]) )
the all() here reinforces the default MATLAB meaning that all of the results of the ismember() must be true for the "if" to succeed. (The result of ismember() is a logical array the same size as the first input, here "daynumbers")
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!