how to compare one element in an array with all the other elements in another array? And repeating it for n elements in the first array?
Afficher commentaires plus anciens
A = [ 1, 2,3,4,5]
B = [ 3,4,2,6,8,0]
Now , take 1st element (i.e = 1) in vector A and compare it with all elements in vector B. And after comparing it with all elements in B and now we need to consider the second element of A ( i.e 2) and do the same. Finish the loop once we iterate with all the elements in the first vector.
6 commentaires
Geoff Hayes
le 6 Avr 2018
Aswin - so once you compare 1 with all elements of B, then what? Are you looking to see if 1 is in B or what?
The easiest - and not the most efficient - is just to have two for loops. The outer loop would iterate over the elements of A and the inner loop would iterate over the elements of B
for j=1:length(A)
a = A(j);
for k = 1:length(B)
b = B(k);
% do something
end
end
dpb
le 6 Avr 2018
And do what with the result of the comparison? How best to do such an operation can depend drastically on what the end result is intended to be.
Aswin Sandirakumaran
le 6 Avr 2018
Modifié(e) : Aswin Sandirakumaran
le 6 Avr 2018
"Iterate it until A element < B element."
And then? Look for more for the same element of A in B or when satisfy the < condition once move to the next?
"So many possibilities, so little defined..."
Given the input arrays, what is the correct final answer desired?
Geoff Hayes
le 6 Avr 2018
Aswin - I think that you need to show what you expect with a small example.
Aswin Sandirakumaran
le 7 Avr 2018
Réponses (1)
dpb
le 6 Avr 2018
A = [ 1, 2,3,4,5]
B = [ 3,4,2,6,8,0]
Taking a guess, and what was written literally,
>> for i=1:length(A)
B(A(i)<B)=B(A(i)<B)-A(i);
end
>> B
B =
2 1 1 3 2 0
>>
Above is repetitive and sequential so the test is repeated on B after the prior elements have already done their duty; hence the second iteration and subsequent operate on an already-modified B.
Above could save a comparison if used a temporary logical vector as
for i=1:length(A)
isLess=(A(i)<B);
B(isLess)=B(isLess)-A(i);
end
which may also be a little easier to read...
2 commentaires
Aswin Sandirakumaran
le 7 Avr 2018
dpb
le 8 Avr 2018
Don't try to create "poof" new variables into the workplace programmatically; use cell arrays to hold the variably-sized results of each step.
Looks to me as though the above example fails in the second step, however, as there are only two elements left in A after the first step so which is <length(B) so length(D) == 2???
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!