Perl PDL : How to change an value in a matrix

141 Views Asked by At

I want to change a value in a PDL matrix :

ex :

my $matrix= pdl [[1,2,3],[4,5,6]];
$matrix->at(0,0)=0;

But this is not working...

Thank you for your help

2

There are 2 best solutions below

0
Håkon Hægland On BEST ANSWER

Here is one approach using range and the .= assignment operator :

my $matrix= pdl [[1,2,3],[4,5,6]];
print $matrix;
$matrix->range([0,0]) .= 0;
print $matrix;

Output:

[
 [1 2 3]
 [4 5 6]
]

[
 [0 2 3]
 [4 5 6]
]

Here is a recent quick introduction to PDL.

0
Ed. On

The most literal answer to the question uses PDL::Core::set:

pdl> p $x = sequence(3,3)

[
 [0 1 2]
 [3 4 5]
 [6 7 8]
]

pdl> $x->set(1,1,19)

pdl> p $x

[
 [ 0  1  2]
 [ 3 19  5]
 [ 6  7  8]
]

However, Håkon's excellent answer does hint at being able to change several (or many) values at once, and that is usually "the PDL way". See https://metacpan.org/pod/PDL::Primitive#whereND for inspiration.