How to Compare two arrays and do something if it is less ? The algorithm should work as below mentioned
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
ag
2025-4-4
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!