59 views (last 30 days)

Show older comments

I have searched the code some time ago, but couldn't find it.

My case is like this.

I have a matrix. eg matrix A. I want to sum the elements of the matrix based on a pattern. The pattern I want is A (a, b) + A (b, g) + A (g, j) + .... So initially we select certain elements from A, for example A (a, b), with row a and column b.

Then the element we select will be added to the next element in the same row number as the column number of the previous element. for example in A (a, b) the column is b, then the next element b will be selected as the row, so that A (b, something from a-b is selected according to the matrix element).

so later there will be some addition 1. A (a, b) + A (b, c) 2. A (a, b) + A (b, d) 3. A (a, b) + A (b, e) etc

This is the example matrix

clc;

clear;

A = [1 2 3 4;

4 3 2 1;

5 2 3 1];

size(A)

thankyou in advance

Jan
on 22 Feb 2021

Edited: Jan
on 24 Feb 2021

A = [1 2 3 4;

4 3 2 1;

5 2 3 1];

Ini = [2, 2];

Fin = [3, 4];

SumAllPaths(A, Ini, Fin);

function S = SumAllPaths(A, Ini, Fin)

% Get linear indices:

iIni = sub2ind(size(A), Ini(1), Ini(2))

iFin = sub2ind(size(A), Fin(1), Fin(2))

Ind = 1:numel(A);

Ind([iIni, iFin]) = []

nInd = numel(Ind);

S = [];

for Len = 1:nInd

% Ordered permutations of elements of A without A(Ini) and A(Fin):

I = nchoosek(1:nInd, Len);

% Does the order matter or not? Maybe (un)comment the next line:

I = reshape(I(:, perms(Len:-1:1)), [], Len);

% [EDITED] Typo, "Result" -> "S"

S = cat(1, S, A(iIni) + sum(A(Ind(I)), 2), A(iFin));

end

end

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

Start Hunting!