Home > OS >  Difference of elements of an array with all element of another array in MATLAB
Difference of elements of an array with all element of another array in MATLAB

Time:01-22

Suppose I have two arrays of different sizes. Say A=[10;12;13;17;18]; and B=[20;22;23;17;26;30;32];. The output, C will be as follows:

   [10, 8,  7,  3,  2;
    12, 10, 9,  5,  4;
    13, 11, 10, 6,  5;
    7,  5,  4,  0,  -1;
    16, 14, 13, 9,  8;
    20, 18, 17, 13, 12;
    22, 20, 19, 15, 14].

Each column of C is obtained by taking difference between all elements of B with a specific element of A. For example, the first column of C is obtained by taking the difference of all elements of B with first element of A, i.e., 10. If the dimension of A is (m-by-1) and B is (n-by-1), then C will have dimension (n-by-m).

CodePudding user response:

you can use this block of code.

clear;
clc;

A=[10;12;13;17;18];
B=[20;22;23;17;26;30;32];

m = length(A);
n = length(B);

C = zeros(n,m);

for i=1:m
    for j=1:n
        C(j,i) = B(j) - A(i);
    end
end

disp(C)
  •  Tags:  
  • Related