Vectorization: incompatible sizes of arrays
2 ビュー (過去 30 日間)
古いコメントを表示
O is a matrix with n_p x n_o rows; P is a matrix with n_p rows. Both matrices have three columns.The second column in O should be filled with the average of two values in the second column of P: the first value at the row ip and the second value at randomly selected row.
counter = 0;
for ip = 1:n_p
for io = 1:n_o
counter = counter + 1;
O(counter,2) = (P(ip,2) + P(randi(n_p),2))/2;
end
end
I attempted to vectorize the code as:
ip = 1:n_p;
io = 1:n_o;
O(ip(:)+io(:),2) = (P(ip(:),2)+P(randi(n_p),2))/2;
I am receiving the following message: „Arrays have incompatible sizes for this operation“. Thank you for any suggestions.
0 件のコメント
採用された回答
Torsten
2022 年 9 月 18 日
編集済み: Torsten
2022 年 9 月 18 日
n_p = 3;
n_o = 3;
P = rand(n_p,2);
R = randi(n_p,n_p*n_o,1)
IP = (cell2mat(arrayfun(@(i)vertcat(repmat(i,1,n_o)),1:n_p,'UniformOutput',0))).'
O(:,2) = (P(IP,2)+P(R,2))/2
3 件のコメント
Bruno Luong
2022 年 9 月 19 日
編集済み: Bruno Luong
2022 年 9 月 19 日
IP = (cell2mat(arrayfun(@(i)vertcat(repmat(i,1,n_o)),1:n_p,'UniformOutput',0))).'
can be simplified to
IP = replem((1:n_p)',n_o)
その他の回答 (2 件)
Bruno Luong
2022 年 9 月 19 日
編集済み: Bruno Luong
2022 年 9 月 19 日
Simpler one liner
O(:,2) = P(randi(end,n_o,end),2) + repelem(P(:,2),n_o) / 2;
0 件のコメント
Bruno Luong
2022 年 9 月 18 日
編集済み: Bruno Luong
2022 年 9 月 18 日
O(:,2) = reshape(reshape(P(randi(end,n_o,end),2),n_o,[]) + reshape(P(:,2),1,[]), [],1) / 2;
2 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!