Message Boards Message Boards

0
|
3277 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Use Which command more concisely

Posted 1 year ago

I defined the following function in my package:

gensFINDSSG//ClearAll;
gensFINDSSG[{m__?MatrixQ} | m__?MatrixQ]:=Block[{gens,dim,vec,x,y,z,t,u,v},
gens={m};
dim=Dimensions[gens][[2]]-1;
Which[
dim==3,vec={x, y, z, 1},
dim==4,vec={x, y, z, t, 1},
dim==5,vec={x, y, z, t, u, 1},
dim==6,vec={x, y, z, t, u, v, 1}
];
 Map[Dot[#, vec] &, gens[[All, 1 ;; dim]], {-2}]// InputForm // ToString //StringReplace[#,{"("->"",")"->""}]&
]

But I want to know if there are more concise ways to rewrite the following part:

Which[
dim==3,vec={x, y, z, 1},
dim==4,vec={x, y, z, t, 1},
dim==5,vec={x, y, z, t, u, 1},
dim==6,vec={x, y, z, t, u, v, 1}
];

Regards, Zhao

POSTED BY: Hongyi Zhao
6 Replies
Posted 1 year ago

My suggestion:

vec=Switch[dim,
  3,{x, y, z, 1},
  4,{x, y, z, t, 1},
  5,{x, y, z, t, u, 1},
  6,{x, y, z, t, u, v, 1}
];
POSTED BY: Hans Milton
Posted 1 year ago

Hi Hans,

Nice trick. Thank you very much.

POSTED BY: Hongyi Zhao

@Hongyi Zhao, every documentation page has "See Also" section. If you would have checked that section for Which you could easily find function Switch and examples of usage there:

https://reference.wolfram.com/language/ref/Which.html?q=Which

POSTED BY: Kapio Letto
Posted 1 year ago

Thank you, Henrik and Daniel,

All the suggested methods work:

In[247]:= Unprotect[x,y,z,t,u,v];
Clear[x,y,z,t,u,v];
vars = {x, y, z, t, u, v};
Append[Take[vars, #], 1]&/@Range[3,6]
%==({x, y, z, t, u, v}[[;; #]]~Join~{1}&/@Range[3,6])

Out[250]= {{x, y, z, 1}, {x, y, z, t, 1}, {x, y, z, t, u, 1}, {x, y, 
  z, t, u, v, 1}}

Out[251]= True
POSTED BY: Hongyi Zhao

One more way for replacing Which:

vec = {x, y, z, t, u, v}[[;; dim]]~Join~{1}
POSTED BY: Henrik Schachner

You can remove the Which like so.

gensFINDSSG // ClearAll;
gensFINDSSG[{m__?MatrixQ} | m__?MatrixQ] := 
 Block[{gens, dim, vec, x, y, z, t, u, v, vars},
  gens = {m};
  dim = Dimensions[gens][[2]] - 1;
  vars = {x, y, z, t, u, v};
  vec = Append[Take[vars, dim], 1];
  Map[Dot[#, vec] &, gens[[All, 1 ;; dim]], {-2}] // InputForm // 
    ToString // StringReplace[#, {"(" -> "", ")" -> ""}] &]

Note that as there was no test example in the question, I have not actually tested this code. So it might require minor changes.

POSTED BY: Daniel Lichtblau
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract