How to multiply each element with next one in the same row, then sum the product

8 views (last 30 days)
I have a matrix with (2^N,N) dimensions, with N be any integer number, and I want to generate a new matrix with (m,s)=(2^N,2) dimensions, where m is just the sum of the elements for each row, and s is the sum of product of each element with its neighbor in the same row. for example
A=[-1 -1;-1 1;1 -1;1 1]
B=(m,s)=[-2 1;0 -1, 0 -1;2 1]
thank you very much

Answers (2)

Arif Hoq
Arif Hoq on 18 Feb 2022
Edited: Arif Hoq on 18 Feb 2022
according to your example, i think s would be only product of each element of a row.
N=2;
AA=randi(10,2^N,3); % random matrix generation
m=sum(AA(:,:),2); % sum of the elements for each row
s=prod(AA(:,:),2); % product of each element
matrix=[m s]
matrix = 4×2
18 150 23 420 13 35 11 21
  6 Comments
Jan
Jan on 18 Feb 2022
Edited: Jan on 18 Feb 2022
Creating a cell array is an expensive indirection usually. You can store the elements directly in a numerical matrix, which is much faster.
You can simplify:
for i=1:1:size(A,2)
if i==4
break
end
to
for i = 1:size(A,2) - 1
With collecting the values in a numerical vector:
m = sum(A, 2);
s = 0;
for i = 1:size(A, 2) - 1
s = s + A(:,i) .* A(:, i+1);
end
output = [m, s];
Or omit even the loop - see my answer.

Sign in to comment.


Jan
Jan on 18 Feb 2022
Edited: Jan on 18 Feb 2022
A = [-1 -1; -1 1; 1 -1; 1 1];
nA = size(A, 2);
B = [sum(A, 2), sum(A(:, 1:nA-1) .* A(:, 2:nA), 2)]
B = 4×2
-2 1 0 -1 0 -1 2 1
The 2nd column of B is the direct "word to word" translation to Matlab of: "sum of product of each element with its neighbor in the same row".
  5 Comments
Jan
Jan on 18 Feb 2022
You are welcome.
It is interesting for learning Matlab to compare the loop with the vectorized version:
% Loop:
m = sum(A, 2);
s = 0;
for i = 1:size(A, 2) - 1
s = s + A(:,i) .* A(:, i+1);
end
% Vectorized:
m = sum(A, 2);
s = sum(A(:, 1:nA-1) .* A(:, 2:nA), 2);

Sign in to comment.

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!