vectorization request with loop

조회 수: 7 (최근 30일)
yoshiyuki
yoshiyuki 2014년 10월 23일
답변: yoshiyuki 2014년 10월 23일
I would like to vectorize the following code with loop
n = 5;
y = (11:20);
for j = 1 : n + 1
for i = 1 : n + 1
if j>= i
func(i,j) = y(i) ./ sum(y(1:j));
end
end
end
Trial>>
Trial>> func
func =
1.0000 0.4783 0.3056 0.2200 0.1692 0.1358
0 0.5217 0.3333 0.2400 0.1846 0.1481
0 0 0.3611 0.2600 0.2000 0.1605
0 0 0 0.2800 0.2154 0.1728
0 0 0 0 0.2308 0.1852
0 0 0 0 0 0.1975
could someone help me out?

채택된 답변

José-Luis
José-Luis 2014년 10월 23일
n = 5;
y = (11:20)';
y_p = cumsum(y)';
result = triu(bsxfun(@rdivide,y(1:n+1),y_p(1:n+1)))

추가 답변 (1개)

yoshiyuki
yoshiyuki 2014년 10월 23일
Thank you so much for very quick answer. sorry to bother you but if I have to add func2, func3 like below n = 5; y = (11:20); for j = 1 : n + 1 for i = 1 : n + 1 if j>= i func(i,j) = y(i) ./ sum(y(1:j)); func2(i,j) = z(j) .* func1(i,j); end end end

카테고리

Help CenterFile Exchange에서 Particle & Nuclear Physics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by