Message Boards Message Boards

Ways to access elements of a list or an array

GROUPS:

Dear All,

For your information only.

A code to access elements of a list or an array.

Grid[{
  {"Description\n\nUsage with:\nmatx={{2,3,5},{7,11,13},{17,19,23}},\n\
b={6,1,8,-4}", "Mathematica function", "Expression", "Output"}
  , {"Select an element", " - ", "b[{3]]\nmatx[[2,3]]", "8\n13"}
  , {"Select a row", " - ", "matx[[2]]", "{7,11,13}"}
  , {"Select a column", " - ", "matx[[All,1]]", "{2,7,17}"}
  , {"Select a submatrix", " - ", "matx[[2;;3,1;;2]]", 
   "{{7,11},{17,19}"}
  , {"Select the first element", "First[list]", "First[b]", "6"}
  , {"Select the last element", "Last[list]", "Last[b]", "-4"}
  , {"Select the first row", "First[mat]", "First[matx]", "{2,3,5}"}
  , {"Select the last row", "Last[mat]", "Last[matx]", "{17,19,23}"}
  , {"Take the first n elements of a list", "Take[list,n]", 
   "Take[b,2]", "{6,1}"}
  , {"Take the last n elements of a list", "Take[list,-n]", 
   "Take[b,-2]", "{8,-4}"}
  , {"Take the nth to kth elements of a list", "Take[list,{n,k}]", 
   "Take[b,{2,4]", "{1,8,-4}"}
  }
 , Alignment -> Left
 , Frame -> {{Red}, {Red}}
 , Background -> {{Lighter[Yellow, .9]}, {Lighter[Yellow, .9]}, None}
 , Spacings -> {3, 2}
 , Dividers -> All
 , ItemStyle -> Directive[FontSize -> 16, Bold]
 , FrameStyle -> Thick]
Print[Style[
  "mat = array of mXm elements,m > 1\nlist = list of m elements\nn, k \
= integer", 18, Red, Bold]]

enter image description here

Cheers,.....Jos

POSTED BY: Jos Klaps
Answer
2 months ago

Thanks for sharing the overview. Other ways of accessing elements would be Extract, and a special case Diagonal. Last elements can also be obtained by Part using -1 as the index. Then there is also the special case: the index = 0 to get the head.

POSTED BY: Sander Huisman
Answer
2 months ago

Hi Sander,

Thanks for your reply and your information.

I was not aware about the functions of 'Extract" and "Diagonal". Thanks for these tips !

Best Regards,....Jos

POSTED BY: Jos Klaps
Answer
2 months ago

You must correct an error in the second row - third column. It must be $b[[3]]$ instead of $b[{3]]$.

POSTED BY: Valeriu Ungureanu
Answer
2 months ago

Hi Valetiu,

Thanks to let me know. Sorry for the typo.

Best Regards,....Jos

POSTED BY: Jos Klaps
Answer
2 months ago

Can we use these with an Excel file ? I want to extract and export elements from a specific range of a spreadsheet in an Excel file. I know that I can use "Import" and "Export" but I would like to put them in a specific case (for example, from B7 to B13)

POSTED BY: Narjes Kandil
Answer
2 months ago

@ I van Veen: thanks for the update in MatrixForm.

@ Hi Narjes,

What have you tried? To understand you correctly, please post your code and Excel file in the future.

This should work: 1 = the first sheet, 7;;13 = from row 7 to row 13, 2 = column 2.

Import["C:\\Users\\.....Directory\\filename.xlsx"][[1, 7 ;; 13, 2]]

I hope this will help !

Best Regards,..... Jos

POSTED BY: Jos Klaps
Answer
2 months ago

Hi, it actually helped me, thank you. Now to export. Well here is my code :

Module[
 {
  \[Alpha] = 50,
  \[Beta] = 100,
  c = 10,
  b = 0.05,
  e = 100,
  k = 100,
  a = 10000,
  s = Import[
     "C:\Users\User\Desktop\PFE\31instances de Tmoy\emissions \
adjustment\Classeur1.xlsx"][[1, 7 ;; 13, 2]],
  t = 0.01*s,
  m,
  f
  },
 (*m=(a+ \[Alpha] p[[n-1]]- \[Alpha] c - (Length[t]-n) \
a)/(\[Alpha](b+(Length[t]-n+1)t[n]- Sum[t[[i]],{i,n+1, Length[t]}]));*)


 f[x0_, pList_] := (pList[[1]] - 
      c - (b + t[[1]]) x0) (a - \[Alpha] pList[[1]]) +
   Sum[ (pList[[i]] - 
       c - (b + t[[i]]) x0) (a - \[Beta]  pList[[
         i]] + \[Beta]  pList[[i - 1]] - \[Alpha] pList[[i]]), {i, 2, 
     Length[t]}] - k (e - x0)^2;


 Maximize[
  {f[\[FormalX], Array[\[FormalP], Length[t]]],
   And @@ Thread[Array[\[FormalP], Length[t]] > 0] && 
    And @@ Table[
      a - \[Beta] (\[FormalP][i] + \[FormalP][
            i - 1]) - \[Alpha] \[FormalP][i] > 0, {i, 2, 5}]
    && (\[FormalX] > 0)
   },
  Flatten[{\[FormalX], Array[\[FormalP], Length[t]]}]
  ]
 ]

Now I want to export the results (values of f, x and p(n)) in the Excel file I have joined below, in specific rows. How do I do that ?

Attachments:
POSTED BY: Narjes Kandil
Answer
2 months ago

Hi Narjes, Where in the XLS do you want to place the results exactly? In a new Sheet with a new name like Results?

Your code gives:

enter image description here

Is that what you want? The formal declarations are not available in the fonts of XLSX so I get garbage.

POSTED BY: l van Veen
Answer
2 months ago

Hi, Actually no, it is not what i want. I think I can not assign the values I imported from the xls file to a variable I can use in the program. For the results, I would like to put them in the spreadsheets already in the file, in the columns where there is D2. In each spreadsheet I have results to put in many columns..

POSTED BY: Narjes Kandil
Answer
2 months ago
data = Import["c:\\Users\\lvveen\\Documents\\Classeur1.xlsx"];
sheetnames =  Import["c:\\Users\\lvveen\\Documents\\Classeur1.xlsx", "Sheets"]

{"Feuil1", "Feuil2", "Feuil3", "Feuil4", "Feuil5", "Feuil6"}

(*generate dummy results per sheet*)
results =  Map[{# <> " resultat 1", # <> " resultat 2", # <> " resultat 3"} &,sheetnames]

{{"Feuil1 resultat 1", "Feuil1 resultat 2", "Feuil1 resultat 3"}, {"Feuil2 resultat 1", "Feuil2 resultat 2", "Feuil2 resultat 3"}, {"Feuil3 resultat 1", "Feuil3 resultat 2", "Feuil3 resultat 3"}, {"Feuil4 resultat 1", "Feuil4 resultat 2", "Feuil4 resultat 3"}, {"Feuil5 resultat 1", "Feuil5 resultat 2", "Feuil5 resultat 3"}, {"Feuil6 resultat 1", "Feuil6 resultat 2", "Feuil6 resultat 3"}}

(*Insert the data at row 3 column 4 (D3)*)
data[[All, 3, 3 ;; 5]] = results

(*Build the new xlsx with the labels from the orignal xlsx.
Each sheet name points to the data for that sheets*)
exportdata = Block[{cnt = 1}, Map[(# ->  data[[cnt++]]) &, sheetnames]];

Export["results.xlsx", exportdata]
Attachments:
POSTED BY: l van Veen
Answer
2 months ago
exportdata = Block[{cnt = 1}, Map[(# ->  data[[cnt++]]) &, sheetnames]];

You like to live dangerously ;-) I prefer a more succinct solution:

exportdata = MapThread[Rule, {sheetnames, data}]
POSTED BY: Sander Huisman
Answer
2 months ago

@Sander, Oh that MapThread.. Yes I agree it's way more elegant. So used to counters from the old days.. I'll put a "MAPTHREAD" tattoo on my arm to not forget :)

POSTED BY: l van Veen
Answer
2 months ago

Great Jos, What I need to use a lot when working from xls or csv files is to pick a number of rows or columns. So in your example:

enter image description here

suppose I need column 1, column 3 and column 2 (in that order)

matx[[All,{1,3,2}]]

enter image description here

Now suppose I need first row1, then row3, then row2 and again row1

matx[[{1,3,2,1}]]

enter image description here

POSTED BY: l van Veen
Answer
2 months ago

@ I van Veen: thanks for the update in MatrixForm.

@ Hi Narjes,

What have you tried? To understand you correctly, please post your code and Excel file in the future.

This should work: 1 = the first sheet, 7;;13 = from row 7 to row 13, 2 = column 2.

Import["C:\\Users\\.....Directory\\filename.xlsx"][[1, 7 ;; 13, 2]]

I hope this will help !

Best Regards,..... Jos

POSTED BY: Jos Klaps
Answer
2 months ago

Group Abstract Group Abstract