Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a 2-d array in Matlab?

I want to make a 2D array dij(i and j are subscripts). I want to be able to do dij = di,j-1+(di,j-1 - di-1,dj-1)/(4^j-1) My idea for this it to make to 1D arrays and then combine them into a 2D array. Is there an easier way to do this?

like image 722
Ben Fossen Avatar asked Feb 27 '23 09:02

Ben Fossen


2 Answers

Since n is 10, I would definitely just preallocate the array like this:

d = zeros(n,n)

Then put in your d(1,1) element and handle your first row explicitly (I'm guessing that you just don't include the terms that deal with the previous row) before looping through the rest of the rows.

like image 153
Justin Peel Avatar answered Mar 10 '23 01:03

Justin Peel


Keep in mind that matlab starts numbering from 1. Then, useful functions are

zeros(m,n) % Makes a 2D array with m rows and n columns, filled with zero
ones(m,n)  % Same thing with one
reshape(a , m , n)   % Turns an array with m*n elements into a m,n square

The last one is useful if you construct a linear array but then want to make a square one out of it. (If you want to count up columns instead of rows, reshape(a,n,m)'.

You can also perform an outer product of two vectors:

> [1;2;3]*[1 2 3]
ans =

   1   2   3
   2   4   6
   3   6   9

To actually build an array with the math you're describing, you'll probably have to loop over it in at least one axis with a for loop.

like image 31
Rex Kerr Avatar answered Mar 10 '23 02:03

Rex Kerr