# Saving data to an array in sage

Hi,

How can I save data to an array in sage. For example in MATLAB we car make an array of data like this

a =0;

for i=1:10

a = a + 1;

b(i,:) = a

end

Similarlay how can I save data in 2D array.

Thanks

edit retag close merge delete

Sort by » oldest newest most voted

Here are two approaches.

Building each row as a list...

b=0
c=[]
for i in [1..10]:
tmp=[]
for j in [1..10]:
b+=1
tmp.append(b)
c.append(tmp)
d=matrix(c)
print d
d[0,1]


Using nested list comprehensions...

c=[[10*j+i for i in [1..10]] for j in [0..9]]
d=matrix(c)
d

more

I don't know here whether you would prefer a list or a matrix or an array as your final data type. But, here is one solution that first builds a list, in case you'd rather have a list. I'm sure there are many other more efficient solutions depending on what you want in the larger picture of what you are doing.

a=0
b=[]
for i in [1..10]:
a+=1
b.append(a)
matrix(b)

more

Thanks for the answer. Suppose I want to create a 2D matrix and I have to access its rows or columns or an individual elements. My data type caan be int/float/real number. What can be a solution in this case. An equivalent MATLAB code can be like this.

a = 0

b = 0

c = 0

for i = 1:10

for j = 1:10

b = b +1

c(i,j) = b

end

end

d = c(1,2)


Sorry I am quite new user of sage.

more

Thank you very much @calc314

more