access the respective values of matrix using the cell array cell position value

i have a matrix as shown in figure, with positions marked
I have a cell array with values
{ [ 1 4 ] ; [ 2 3] };
Now i want to take the values from position
{ [0-1 1-4] ; [0-2 2-3] } of the matrix
i.e. { [ 33 45]; [34 30] }
and get the sum of
33 + 45 +34 +30 = 142
how can i access the respective values of matrix using the cell array cell position values?

 Réponse acceptée

Hi Elysi,
Here is what you have asked for
% Given matrix
a = [0 33 34 16 25;...
22 0 20 12 45;...
20 40 0 30 12;...
16 12 30 0 44;...
34 56 26 15 0];
% Cell positions
cellValue = {[1, 4], [2 3]};
% To make it generic, for any number of cell elements with varying size, you can use a for loop
s=0;
for i = 1:numel(cellValue)
cellInd = cellValue{i};
tmp = [];
tmp(1) = a(0+1,cellInd(1)+1);
for j = 2:length(cellInd)
tmp = [tmp a(cellInd(j-1)+1,cellInd(j)+1)];
end
s = sum(tmp) + s;
end
Hope this helps.
Regards,
Sriram

5 commentaires

sir why output not coming correct for this example, the sum should be 241, when doing manually, but using the code i get 180 only
cellValue = { [1 4 2] [3 1 4] [2 3] };
[ 0-1 1-4 4-2
0-3 3-1 1-4
0-2 2-3]
33 45 26
16 12 45
34 30
Total sum = 241
Ok sure. I wasn't aware from the problem that the cell array can vary its dimensions.
So, here is the modified code for it
s=0;
for i = 1:numel(cellValue)
cellInd = cellValue{i};
tmp = [];
tmp(1) = a(0+1,cellInd(1)+1);
for j = 2:length(cellInd)
tmp = [tmp a(cellInd(j-1)+1,cellInd(j)+1)];
end
s = sum(tmp) + s;
end
Hope this helps
sir answer is coming 251
but answer is 241
Ya. Please take the latest code in the answer. I had written one value wrong in the matrix and that 10 increase is due to it. If you see the first row and third column of matrix a, it is written as 26 instead of 16.I did correct in it in the answer, take the latest code and check.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by