How to Compare two arrays and do something if it is less ? The algorithm should work as below mentioned
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
A=[1,2,3,4,5] B=[6,7,8] then the code should take the 1st element in A (ie. 1) and compare it with B, if ( the first element is smaller (A<B) do B - A and store that value in a new array. Then go for the 2nd Element in A (ie. 2) and compare it with 2nd element in array B ( 2< 7) therefore do B - A and store it in C[2]. and so on
A = [1,2,3,4,5] B = [6,7,8] % C should be the new result after comparing A[i] < B[i] C[i] = B[i] - A[i]; C = [5,5,5] Once done we are left with 4th,5th element in array A. if length of array A exceeds length of array B. Then the elements after length of A = length of array B should comparing from the index 1 of array C. But now it should compare with the new C element A = [4,5] % new A C = [5,5,5] % new C repeat the same process as above while comparing and get new array Final Result: D = [1,0,5]
0 Kommentare
Antworten (1)
ag
am 4 Apr. 2025
Hi Aswin,
To achieve this, you can implement a loop that handles the comparison and subtraction operations. The logic involves iterating over the elements of array A and comparing them with corresponding elements in B and then C, as described.
The below code snippet demonstrates how to achieve the same:
% Initialize array C to store differences between A and B
C = zeros(1, length(B));
% Compare elements of A with B and compute differences
for i = 1:length(B)
if A(i) < B(i)
C(i) = B(i) - A(i);
end
end
% Extract the remaining elements of A that exceed the length of B
remainingA = A(length(B) + 1:end);
% Initialize array D to store results of comparisons with C
D = zeros(1, length(remainingA));
% Compare remaining elements of A with elements in C, cycling through C
for i = 1:length(remainingA)
index = mod(i - 1, length(C)) + 1; % Cycle through C using modulo
if remainingA(i) < C(index)
D(i) = C(index) - remainingA(i);
end
end
For more details, please refer to the following MathWorks documentation: mod - https://www.mathworks.com/help/matlab/ref/double.mod.html
Hope this helps!
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!