访问PDL对象中数据的最佳实践

发布于 2025-02-13 07:01:28 字数 195 浏览 0 评论 0原文

例如,我有一个2维的PDL:

my $data  = random(4,4);

我想计算PDL上下文之外的0,0和1,0元素的总和。 (例如$ data-> slice('0,0') + $ data-> slice('1,0),它仍然返回PDL对象) 正确的方法是什么?

I have a 2 dimensional pdl,for example:

my $data  = random(4,4);

and I want to compute the sum of the 0,0 and the 1,0 element outside of the pdl context.
(Not like, for example $data->slice('0,0') + $data->slice('1,0), which still returns a pdl object)
What is the correct way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

箜明 2025-02-20 07:01:28

如果您想将单个元素作为普通perl标量提取,请在上使用 slice :

pdl> $pdl = random(4,4)
pdl> p $pdl->at(0,0) + $pdl->at(1,0)
0.288796754210711
pdl> p ref \($pdl->at(0,0) + $pdl->at(1,0))
SCALAR

将整个ndarray对象转换为嵌套的perl数组,请使用umpdl

pdl> $aoa = random(4,4)->unpdl;
pdl> p ref $aoa
ARRAY
pdl> p ref $aoa->[0]
ARRAY

请注意,perl数组中元素的索引是在ndarray对象中完成的横向。例如,

pdl> p $pdl->at(1,0)
0.111869023064209

pdl> p $aoa->[1][0] # wrong
0.954887281829823

pdl> p $aoa->[0][1] # correct
0.111869023064209

If you're looking to extract individual elements as normal Perl scalars, use at instead of slice:

pdl> $pdl = random(4,4)
pdl> p $pdl->at(0,0) + $pdl->at(1,0)
0.288796754210711
pdl> p ref \($pdl->at(0,0) + $pdl->at(1,0))
SCALAR

To convert the entire ndarray object into nested Perl arrays, use unpdl

pdl> $aoa = random(4,4)->unpdl;
pdl> p ref $aoa
ARRAY
pdl> p ref $aoa->[0]
ARRAY

Note that the indexing of elements in the Perl arrays is the transverse of that done in the ndarray objects. For example,

pdl> p $pdl->at(1,0)
0.111869023064209

pdl> p $aoa->[1][0] # wrong
0.954887281829823

pdl> p $aoa->[0][1] # correct
0.111869023064209
迟到的我 2025-02-20 07:01:28

Diab的答案非常适合所问的问题。但是,由于问题包括询问“最佳实践”,我建议通常在使用PDL时,应该考虑以阵列编程样式立即考虑所有操作,并且/或考虑您的代码在给出更高的情况下如何运行 - 维度ndarrays(即它将如何“广播”)。

一种使给定代码广播的方法,以便将4x4的1个元素ndarray归还,但是如果给出了4x4x3 ndarray:3元素:

use PDL;
sub sum_top_left { $_[0]->slice('(0),0:1')->sumover }
print $data = sequence(4,4) + 3;
print sum_top_left($data);
print $data = sequence(4,4,3) + 3;
print sum_top_left($data);

Diab's answer is perfect for the question as asked. However, since the question includes asking about "best practice", I would recommend that usually when using PDL, one should consider operating on everything at once, in array-programming style, and/or to consider how your code would operate when given higher-dimensional ndarrays (i.e. how it would "broadcast").

A way to make the given code broadcast so that it would give back a 1-element ndarray for a 4x4, but a 3-element if given a 4x4x3 ndarray:

use PDL;
sub sum_top_left { $_[0]->slice('(0),0:1')->sumover }
print $data = sequence(4,4) + 3;
print sum_top_left($data);
print $data = sequence(4,4,3) + 3;
print sum_top_left($data);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文