gpt4 book ai didi

matlab - 将 C 风格代码转换为 Matlab

转载 作者:行者123 更新时间:2023-12-04 04:45:45 24 4
gpt4 key购买 nike

我在 C 中有以下代码:

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
a[b[i]][c[j]]+=1;
}
}

有没有办法在不使用 for 循环的情况下在 Matlab 中编写它?我的意思是使用 (:) 更快的 Matlab 方式。

类似 a(b(:),c(:))=a(b(:),c(:))+1给我内存不足错误。

最佳答案

有趣。虽然我(还)没有为您提供解决方案(底部的解决方案),但我有一些注意事项和提示:

1. 内存不足错误是因为您在右侧创建了一个 512*256 x 512*256 元素的临时矩阵 ( a(b(:),c(:))+1 )。那是 2^34 字节 — 17GB!这就是为什么您会出现内存不足错误的原因。还要注意,这个数组甚至不是你想要的!看这个例子:

>> a = magic(5);
>> b = [1 5 4]; % The rows that contain the numbers 1,2,3 respectively
>> c = [3 4 5]; % The columns that contain ^ ...

现在,a(1,3) == 1, a(5,4) == 2 等等。但是当你说 a(b,c) ,您正在为这些行中的每一行选择行 (1,5,4) 和列 (3,4,5)!
>> a(b,c)
ans =

1 8 15
25 2 9
19 21 3

你关心的只是对角线。解决方法是使用 sub2ind将您的下标对转换为线性索引。
>> a(sub2ind(size(a),b,c))
ans =

1 2 3

2. 您提出的解决方案也没有按照您的意愿行事。由于 Matlab 缺少增量运算符,您只需将 (b,c) 中存在的所有索引加一。没有了。将其矢量化需要一些创造性思维。使用较小的数组来查看发生了什么:
>> a = zeros(4,4);
>> b = ones(8,4);
>> c = ones(8,4);
>> a(b,c) = a(b,c) + 1;
>> a
a =

1 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

编辑 我们走吧!向量化增量:
>> idxs = sub2ind(size(a),b(:),c(:)); % convert subscripts to linear indices
>> [unique_idxs,~,ic] = unique(idxs); % Get the unique indices and their locations
>> increment_counts = histc(ic,1:max(ic)); % Get the number of occurrences of each idx
>> a(unique_idxs) = a(unique_idxs) + increment_counts;

关于matlab - 将 C 风格代码转换为 Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18215214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com