My own code (for the following aim) which I think is not so good written is:
Do[desired[k] = 0;
Do[
Do[
If[list1[[i]] == list2[[j]], desired[k] += matrix[[i, j]]]
, {i, 1, Length@list2}]
, {j, 1, Length@list1}]
, {k, 1, 5}]
Please see two below lists (8*5) (which are equal to each other):
list1 = {{1, 0, 0, 3, 0}, {1, 0, 0, 3, 0}, {3, 0, 0, 2, 0}, {3, 0, 0,
1, 0}, {2, 0, 0, 3, 0}, {3, 0, 0, 3, 0}, {3, 0, 0, 3, 0}, {3, 0,
0, 2, 0}};
list2 = {{1, 0, 0, 3, 0}, {1, 0, 0, 3, 0}, {3, 0, 0, 2, 0}, {3, 0, 0,
1, 0}, {2, 0, 0, 3, 0}, {3, 0, 0, 3, 0}, {3, 0, 0, 3, 0}, {3, 0,
0, 2, 0}};
Some elements of these matrices are equal, For instance: {1, 0, 0, 3, 0}, {1, 0, 0, 3, 0}
. For the future, I take i
index from the first list and j
from the second list.
I have another matrix as
matrix={{7, 6, 9, 9, 8, 8, 10, 10}, {6, 8, 10, 6, 6, 6, 6, 8}, {8, 9, 6, 8,
6, 9, 5, 8}, {5, 9, 7, 6, 7, 7, 5, 8}, {10, 5, 10, 8, 8, 5, 10,
6}, {10, 9, 5, 5, 10, 8, 8, 7}, {7, 6, 7, 10, 7, 9, 7, 8}, {6, 7, 6,
5, 7, 8, 7, 10}}
It is an 8*8 matrix.
I am going to try sum over some elements of the matrix that their indices are obeyed by the equality of the rows of the two upper lists: (sum over matrix[[i,j]]
in which i
is from the first list and j
from the second one).I mean
(*{1,0,0,3,0}*)
desired[1] = matrix[[1, 1]] + matrix[[1, 2]] + matrix[[2, 1]] + matrix[[2,2]];
(*{3,0,0,2,0} *)
desired[2] = matrix[[3, 3]] + matrix[[3, 8]] + matrix[[8, 3]]+ matrix[[8, 8]];
(*{3,0,0,1,0}*)
desired[3] = matrix[[4, 4]];
(*{2,0,0,3,0} *)
desired[4] = matrix[[5, 5]];
(*{3,0,0,3,0}*)
desired[5] =matrix[[6, 6]] + matrix[[6, 7]] + matrix[[7, 6]] + matrix[[7, 7]];
for the last case ((*{3,0,0,2,0}*))
we do not need a new calculation because it was considered.
Is an efficient code? Also I put the {k, 1, 5}
by hand. I saw that the k
cannot exceed form 5
.
list1
andlist2
)? Can they be different? What iflist1
has a value which is absent fromlist2
? $\endgroup$ – jjc385 Jul 5 '17 at 20:35i
andj
$\endgroup$ – Unbelievable Jul 5 '17 at 20:37list1
andlist2
are different. Supposematrix={{a,b},{c,d}}
andlist1={x,y}
whilelist2={y,z}
. What is the desired output? Is itdesired[1] = matrix[[2,1]]
? $\endgroup$ – jjc385 Jul 5 '17 at 22:20