A simple way:
sensMat[n_] := Table[If[i == j, 1, (n - 1)*0.1], {i, 1, 5}, {j, 1, 5}]
A funny way:
sensMat[n_] := NestList[RotateRight, Join[{1}, ConstantArray[(n - 1)*0.1, 4]], 4]
For memorization benefits (and inconvenients):
sensMat[n_] := sensMat[n] = (*your preferred code here*)
-----EDIT-----
Nobody warned me that we were shooting for speed :-), so here is the funny speedy way:
sensMat =
Compile[{{n, _Integer, 0}, {dimension, _Integer, 0}, {step, _Real,
0}}, NestList[RotateRight,
Join[{1}, ConstantArray[(n - 1)*step, dimension - 1]],
dimension - 1]]
AbsoluteTiming[sensMat[3, 10000, 0.1];]
(* {1.670095, Null} *)
In comparison with whuber's solution:
f[r_, n_Integer /; n > 0] :=
ConstantArray[r, {n, n}] + DiagonalMatrix[ConstantArray[1 - r, n]]
AbsoluteTiming[f[0.2, 10000];]
(* {2.828162, Null} *)
(On latter runs, this version gave timings virtually equal to the ones I got with the compiled sensMat)
This last solution doesn't gain anything from compilation (as expected...):
fCom = Compile[{{r, _Real, 0}, {n, _Integer, 0}},
ConstantArray[r, {n, n}] +
DiagonalMatrix[ConstantArray[1 - r, n]]];
AbsoluteTiming[fCom[0.2, 10000];]
(* {2.840162, Null} *)
Just to make sure:
sensMat[3, 10000, 0.1] == fCom[0.2, 10000]
(* True *)
Interesting enough, this is the first case I found where WVM is faster than C
sensmat = Table[DiagonalMatrix[{1, 1, 1, 1, 1}] /. (0 -> i), {i, 0, 1, 0.1}];seems simple enough – ssch Jan 6 at 13:38sensmat[[1]]will be the identity matrix and the zeros will increase up until it's all ones insensmat[[11]].And @@ (Dimensions[#] == {5, 5} & /@ sensmat) (* True *)– ssch Jan 6 at 15:57