3
$\begingroup$

I have the dimensions of a matrix A. I would like to create a matrix B (say, of only 0's) of the same size as A. But A's dimensions are variable. Is there an efficient way using d = Dimensions[A]?

I could use

B =  Table[0, {i, d[[1]]}, {j, d[[2]]}]

or

B = A; 
B[[All, All]] = 0; 

but I would like to generalize the algorithm to work if the order of A is also variable (like 3rd order tensor and so on).

In MATLAB, what I'm asking for would be zeros(size(A)).

$\endgroup$
7
$\begingroup$

How about this:

a = ConstantArray[1, {4, 4}]

(* ==> {{1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}} *)

b = ConstantArray[0, Dimensions[a]]

(* ==> {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}} *)
$\endgroup$
6
$\begingroup$

If your matrix has no expressions in level -1, this could work for any matrix.

a={{1,2,{3}},{5,6,{7,{8,9}}}}

b=Replace[a,_->0,{-1}]

(*{{0,0,{0}},{0,0,{0,{0,0}}}}*)

You could also do simple multiplication by 0

a*0

(*{{0,0,{0}},{0,0,{0,{0,0}}}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.