How to add elements to the matrix with a certain pattern?
20 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
10 Comments
Jan
on 22 Feb 2021
In other words: You select two different elements of the matrix (randomly?). Then you want to obtain all permutations (no repetitions, but does the order matter?) (or just some random ones?) of the other elements with 0 to numel(A)-2 elements. Finally you want to add the elements and maybe collect the output in a vector?
Is this correct? Then please define the missing details in the parentheses.
You mention the additions, but what is the wanted result?
Answers (1)
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
6 Comments
Jan
on 24 Feb 2021
My code replies a lot of equal values, if you enable the coutung of the permutations:
sum(A([1,2,3])) == sum(A([1,3,2])) == sum(A([3,2,1])) ... and so on
You did not give an example yet and so I have to guess, if this is wanted or not. If you do not want to count the permutations, comment this line:
I = reshape(I(:, perms(Len:-1:1)), [], Len);
See Also
Categories
Find more on Creating and Concatenating Matrices 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!