필터 지우기
필터 지우기

Build array from descriptive data without a loop

조회 수: 1 (최근 30일)
Gabriel Stanley
Gabriel Stanley 2023년 2월 17일
댓글: Walter Roberson 2023년 2월 17일
I want to go from
Array1 = [10,3,3;1000,178,4];
to
Array2 = [10;13;16;1000;1178;1356;1534];
without using
Idx2 = 1;
Array2 = zeros(sum(Array1(:,3)),1);
for Idx1 = 1:size(Array1,1)
Array2(Idx2:Idx2+Array1(Idx1,3)-1) = [Array1(Idx1,1),Array1(Idx1,1)+[1:Array1(Idx1,3)-1].*Array1(Idx1,2)];
Idx2 = Idx2+Array1(Idx1,3)-1;
end
Help?

채택된 답변

Walter Roberson
Walter Roberson 2023년 2월 17일
Array1 = [10,3,3;1000,178,4];
Array2 = cell2mat(arrayfun(@(Idx) Array1(Idx,1) + (0:Array1(Idx,3)-1).'*Array1(Idx,2), (1:size(Array1,1)).','uniform', 0))
Array2 = 7×1
10 13 16 1000 1178 1356 1534
  댓글 수: 2
Gabriel Stanley
Gabriel Stanley 2023년 2월 17일
Kinda disappointed this hasn't ended up being significantly faster in my use-case, but thank you for providing an answer. I never would've thought to use arrayfun (or cellfun & the like) because I've gotten the impression they're generally slower than a loop.
Walter Roberson
Walter Roberson 2023년 2월 17일
You didn't ask for performance, you asked for not using a loop. For most operations (but not all, not if you know the right obscure forms), arrayfun and cellfun are slower than looping.
If you were looking for performance, then your existing code could be tweeked to take advantage of cumsum() instead of calculating the indices each time, and you could use the calculation I used instead of using [original, colon expression] list constructor.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Kevin Holly
Kevin Holly 2023년 2월 17일
Array1 = [10,3,3;1000,178,4];
Array2 = cumsum(Array1,2)
Array2 = 2×3
10 13 16 1000 1178 1182
  댓글 수: 2
Walter Roberson
Walter Roberson 2023년 2월 17일
Tthe third column is the number of elements to generate, with the difference being the second column, and the starting point being the first column.
Kevin Holly
Kevin Holly 2023년 2월 17일
ah, thanks for pointing that out.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by