I need to perform a number of operations within a For loop and store the results in an indexed array (without using the Append function) For examole (to make it simple), I need to find the square of numbers i = 1 to 5 and sore it in y[i]. In precedural languages it would look like:

   for i = 1,5,i++,

To implement this in Mathematica I tried this code:

 For[i = 1, i <= 5, i++,
    y[[i]] = i^2;  

which failed. Is there a way to create such array (y)?

  • 2
    $\begingroup$ Do you understand why it failed? y is not defined, so you can't access y[[i]]. Try defining y before and it works (for that, see e.g. ConstantArray). Edit My comment assumes, as you state, that you need to use For. Otherwise that's much simpler with Table. $\endgroup$ – anderstood Mar 23 '18 at 16:44
  • 5
    $\begingroup$ You almost never need a For[] loop. Try y = Range[5]^2. $\endgroup$ – J. M. is in limbo Mar 23 '18 at 16:44
  • 2
    $\begingroup$ Or lookup Table. $\endgroup$ – gwr Mar 23 '18 at 16:45
  • 2
    $\begingroup$ Then you should look up Map[] or Table[] as already suggested, if you have a list of images. If you really must loop, use Do[] instead. $\endgroup$ – J. M. is in limbo Mar 23 '18 at 17:09
  • 3
    $\begingroup$ If OP is doing image processing OP should probably be using at least some of Mathematica's image processing functions: Blur, a whole host of Filters, etc. $\endgroup$ – High Performance Mark Mar 23 '18 at 20:33
y = Range[5]; (* y needs to be predefined as anderstood pointed out *)
For[ i = 1, i <= 5, i++,
  (* body *)
  y[[i]] = i^2

If it has to be For...

(* {1, 4, 9, 16, 25} *)
  • $\begingroup$ Thank you so much! $\endgroup$ – Heba Sea Mar 23 '18 at 16:52
  • 2
    $\begingroup$ @HebaSea You are welcome. Be sure to look up the alternatives given in the comments above. For really is no fit for Mathematica. $\endgroup$ – gwr Mar 23 '18 at 16:56

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.