Build array from descriptive data without a loop
1 回表示 (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
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))
2 件のコメント
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
2023 年 2 月 17 日
Array1 = [10,3,3;1000,178,4];
Array2 = cumsum(Array1,2)
2 件のコメント
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.
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!