MATLAB: How to call a specific variable in matrix inside loop process..?

for loopmatrix manipulationvectorizing

I have a little problem with my matrix. Perhaps you interested with this..
I have matrix like below :
xdata = [ 1 2 0.0192
1 3 0.0452
2 4 0.0570
3 4 0.0132
2 5 0.0472
2 6 0.0581
4 6 0.0119
5 7 0.0460
6 7 0.0267
6 8 0.0120
6 9 0.0
6 10 0.0
9 11 0.0 ];
I want to call a variable in that matrix one by one following my loop order. For example :
Q = 0;
K = 0;
n = length(xdata);
i = xdata(:,1);
j = xdata(:,2);
for bb = 1:n,
for cc = 1:n,
c1 = xdata(:,1);
c2 = xdata(:,2);
if c1 == bb,
if c2 == cc,
K = linedata(:,3);
end
end
Q = Q + (K*100);
end
end
so when bb = 1 and cc = 2, K will call xdata(:,3) in line 1 = 0.0192
when bb = 1 and cc = 3, K will call xdata(:,3) in line 2 = 0.0452
when bb = 6 and cc = 7, K will call xdata(:,3) in line 9 = 0.0267, and so on…
My code above are wrong and I feel really dizzy when coding it, maybe you can help me with this..
anyone has the solution..?
thanks…

Best Answer

Here is an answer based on what I understood, and a truncated version of xdata in which I removed the last row that contains an invalid index (11) for indexing B.
It seems to me that what you want to do can be reduced to one vector operation as follows:
>> Q = sum( xdata(:,3) .* (A(xdata(:,1)) - B(xdata(:,2))) )
Q =
0.1059
where the SUM operates along dimension 1 (by default). I will discuss it a little more afterwards, but let's check against a corrected version of your double, nested FOR loop:
>> n = size(xdata, 1) ;
>> Q = 0 ;
>> for bb = 1 : n
for cc = 1 : n
id = xdata(:,1)==bb & xdata(:,2)==cc ;
if any(id)
Q = Q + xdata(id,3) * (A(bb) - B(cc)) ;
end
end
end
>> Q
Q =
0.1059
which seems to match to concise version. In these FOR loops, finally only a few iterations lead to a match of indices. If you look at what we are doing in the concise version,
>> A(xdata(:,1))
ans =
0.9148
0.9148
0.4772
0.9162
0.4772
0.4772
0.4969
0.9276
0.7037
0.7037
0.7037
0.7037
is a vector of elements of A that correspond to these matches. Same for B(xdata(:,2)). By subtracting them, we get in one shot all these factors A(bb)-B(cc), that we can multiply element-wise by all the K's ( xdata(:,3) ). Finally, we take the sum of these products.
Test this/these solution(s) little bit by little bit to get full understanding. Let me know if I didn't understand well what you need, or if there is anything that you don't understand.
Related Question