compare the value of two matrix
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Adam
el 4 de Nov. de 2015
Editada: Adam
el 4 de Nov. de 2015
Not unless you tell us what it is you want the code to do!
I could hazard a guess that if your matrices contain doubles then using == is not a good idea because of floating point precision, but beyond that it is hard to say without knowing what any of the data is.
Respuestas (1)
Walter Roberson
el 4 de Nov. de 2015
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 comentarios
Walter Roberson
el 8 de Nov. de 2015
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")
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!