Reputation: 315
I am currently experimenting with Matlab functions. Basically I am trying to perform a function on each value found in a matrix such as the following simple example:
k = [1:100];
p = [45 60 98 100; 46 65 98 20; 47 65 96 50];
p(find(p)) = getSum(k, find(p), find(p) + 1);
function x = getSum(k, f, g, h)
x = sum(k(f:g));
end
Why the corresponding output matrix values are all 3, in other words why all indices are depending on the first calculated sum?
The output is the following:
p =
3 3 3 3
3 3 3 3
3 3 3 3
Upvotes: 0
Views: 79
Reputation: 316
f:g
returns the value between f(1,1)
and g(1,1)
, so 1:2
.
find(p)
returns the indices of non zero values. Since all values are non-zero, you get all indices.
So if we break down the statement p(find(p)) = getSum(k, find(p), fin(p) + 1)
We get
find(p) = 1:12
We then get
f = 1:12
and g = 2:13
which lead to k = 1:2
(as explained above)
finally sum(1:2) = 3
And this value is apply over p(1:12)
, which is the same as p(:,:)
(all the matrix)
Upvotes: 2