How can I use bsxfun to replace for-loop in this code?
Afficher commentaires plus anciens
Dear all,
I want to use the function 'bsxfun' instead of inner for-loop. My code is as following. However, the result, matrix B, calculated by 'bsxfun' is error. I feel very confused with how 'bsxfun' works. Could anyone help me to understand the result and use 'bsxfun' correctly instead of inner for-loop?
Thanks very much!
sequence = [1,2,3,4,5];
avg = @(i, j) mean(sequence(i:j));
for i = 1:4
for j = i+1:5
A(i,j) = avg(i,j);
end
B(i, i+1:5) = bsxfun(avg, i, i+1:5);
end
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 19 Mai 2017
0 votes
"Binary function to apply, specified as a function handle. fun must be a binary (two-input) element-wise function of the form C = fun(A,B) that accepts arrays A and B with compatible sizes. For more information, see Compatible Array Sizes for Basic Operations. fun must support scalar expansion, such that if A or B is a scalar, then C is the result of applying the scalar to every element in the other input array."
In practice what this means for bxfun(@fun, A, B) is:
- if A and B are the same size(), fun(A,B) is called directly and size(A) = size(B) outputs are expected
- if either A or B are scalars and the other is not, then fun(A,B) is called directly and size() of the non-scalar is the expected output size
- otherwise fun(A(:,K), B(K)) is called once for each column K in A with size(A,1)x1 expected output size
Your case matches the first of those, so avg(i, i+1:5) is going to be called -- but your avg code expects the second input to be a scalar rather than a vector.
3 commentaires
Walter Roberson
le 19 Mai 2017
For R2016b or later:
S = cumsum([0; sequence(:)]);
result = tril((S - S.') ./ ((1:length(S)).' - (1:length(S))),-1);
For earlier:
S = cumsum([0; sequence(:)]);
result = tril( bsxfun(@minus, S, S.') ./ bsxfun(@minus, (1:length(S)).', (1:length(S))), -1);
Shi Shi
le 19 Mai 2017
Shi Shi
le 19 Mai 2017
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!