access array multiple times and calculate some value

조회 수: 1 (최근 30일)
dleal
dleal 2022년 7월 28일
답변: David Hill 2022년 7월 28일
Hi all, I would like to know if there's a faster way that using a foor loop for this:
a = rng(99);
A = randn(1,100);
B = [20 23; 30 37; 51 55; 78 100 ];
For each row B, I would like to slice A from the first column to the second column value, and then apply some function, for example, sum.
So for example, the first computation would be sum(A(20:23)), then sum(A(30:37)) ... sum(A(78:100)).
The for loop would be:
for ii = 1:size(B,1)
sum(A(B(ii,1) : B(ii,1) );
end
Could I program this such that it results in a faster calculation?

답변 (1개)

David Hill
David Hill 2022년 7월 28일
Shorter way to write it, but will not improve speed.
s=arrayfun(@(x)sum(A(B(x,1):B(x,2))),1:size(B,1));

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by