Is MATLAB row specific or column major? - matlab

In MATLAB, we can operate on both rows and columns of a matrix. What does it exactly mean by "row major" or "column major"?

It is important to understand that MATLAB stores data in column-major order, so you know what happens when you apply the colon operator without any commas:
>> M = magic(3)
M =
8 1 6
3 5 7
4 9 2
>> M(:)
ans =
8
3
4
1
5
9
6
7
2
I tend to think "MATLAB goes down, then across". This makes it easy to reshape and permute arrays without scrambling your data. It's also necessary in order to grasp linear indexing (e.g. M(4)).
For example, a common way to obtain a column vector inline from some expression that generates an array is:
reshape(<array expression>,[],1)
As with (:) this stacks all the columns on top of each other into single column vector, for all data in any higher dimensions.
But this nifty syntactic trick lets you avoid an extra line of code.

In MATLAB, arrays are stored in column major order.
It means that when you have a multi-dimensional array, its 1D representation in memory is such that leftmost indices change faster.
It's called column major order because for a 2D array (matrix), the first (leftmost) index is typically the row index, so since it changes faster than the second (next to the right) index, the 1D representation of the matrix is memory correspond to the concatenation of the columns of the matrix.

Related

Stack a n x n matrix to from a n^2 x 1 column matrix

for a 5 x 10 matrix, I wanted to stack the matrix in such a way that each column of the original matrix will be appended to the rows to finally end up with a 50 x 1 matrix. Basically stack the columns into 1 column. Thanks.
Here is the start of the matrix:
RR = randi(5,5,10);
For general reshaping operations, use reshape, for example:
reshape(RR,[],1)
This reshapes the array RR into an array with an indeterminate number of rows (the []) and 1 column, as you need.
Your particular case can use the shortcut mentioned by #beaker in the comments
RR(:)
This syntax is equivalent to the reshape command above, and simply lists, in one column, all elements of the array.
Both of these examples take advantage of the fact that Matlab uses column oriented storage and indexing. If, for some reason, you need to concatenate rows rather than columns, you would need to transpose the RR array first. For example:
reshape(RR', 1, []) %This concatenates the rows of RR into a single row. Note the transpose operator.

alternative to reshape or colon in matlab

I want to reduce a two dimensional matrix to row vector.
But using reshape with large matrices is really slow. The other alternative is to use colon, but i want matrix's transpose to be colon and not the matrix itself.
e.g.
A=magic(3)
A =
8 1 6
3 5 7
4 9 2
A(:) will stack up all the columns one by one. but i am looking for something like this:
AA=A(2:3,:)';
and then reshape or colon AA instead of A.
The issue is i dont want to define additional variable like AA.
Is there anyway to reduce dimension of two dimensional matrix without reshape?
You can avoid the additional variable by linear indexing. For your example:
A([2 5 8 3 6 9])
which gives
3 5 7 4 9 2
What's happening here is that you treat A as if it was already transformed into a vector, and the elements of this one-dimensional array are accessed through indices 1 through 9. Using the colon is a special case of linear indexing, A(:) is the same as A(1 : end).
Figuring out the right linear indices can be tricky, but sub2ind can help with that.
It is possible that this slightly speeds up the code, mainly because (as #Shai wrote) you avoid writing data to an intermediate variable. I wouldn't expect too much, though.
Try looking at subsref. For your example, you could use it as follows:
subsref(A',struct('type','()','subs',{{2:3,':'}}))
Update: I misunderstood the original question; I thought the OP wanted to select rows from 2:3 from the transposed A matrix keeping the columns as is. I will keep the previous answer in case it could be useful to others.
I think he/she could use the following to slice and flatten a matrix:
subsref(A(2:3,:)', struct('type','()','subs',{{':'}}))
This would give as output:
[3 5 7 4 9 2]'

how to sum matrix entities as indexing by another vector values?

Suppose I have a vector B=[1 1 2 2] and A=[5 6 7 4] in the form of B says the numbers in the A that are need to be summed up. That is we need to sum 5 and 6 as the first entry of the result array and sum 7 and 4 as the second entry. If B is [1 2 1 2] then first element of the result is 5+7 and second element is 6+4.
How could I do it in Matlab in generic sense?
A fexible and general approach would be to use accumarray().
accumarray(B',A')
The function accumulates the values in A into the positions specified by B.
Since the documentation is not simple to understand I will summarize why it is flexible. You can:
choose your accumulating function (sum by default)
specify the positions as a set of coordinates for accumulation into ND arrays
preset the dimension of the accumulated array (by default it expands to max position)
pad with custom values the non accumulated positions (pads with 0 by default)
set the accumulated array to sparse, thus potential avoiding out of memory
[sum(A(1:2:end));sum(A(2:2:end))]

How to change elements in matrices using MATLAB

Starting wish a 7x4 binary matrix I need to change a random bit in each column to simulate error. Have been trying to no avail.
A very straightforward way to do this is to use a for loop. It might not be the most efficient approach in MATLAB, but it's probably good enough considering your data set is so small.
Iterate through each of the four columns. On each iteration, randomly chose a number from 1 to 7 to represent the row in that column that you have selected to change. Finally, flip the bit at that row/column. The following code does just this. Assume that "A" is a binary matrix with 7 rows and 4 columns
for col=1:4; %// Iterate through each column
row = ceil(7*rand()); %// Randomly chose a number from 1 to 7 to represent row
A(row,col) = ~A(row,col); %// Flip the bit at the specified row/col
end
Another possibility is to create 4 random numbers in one call, and assign in a vectorized fashion:
rowNumbers = randi(4,[1 4])
A(rowNumbers,:) = ~A(rowNumbers,:);

how this code is used in matlab for Artificial Intelligence

i am trying this code since last night but i cant understand what this code is doing. actually i am beginner in matlab programming
load('79.mat')
trainingData=d79;
colormap(gray);
colormap(grey);
x=reshape(d79(1234,:),28,28);
y = x(:,28:-1:1);
pcolor(y');
Kindly help me in understanding this code. :/
This is pretty simple. Here is a line-by-line explanation:
Loads data from a data file
Puts the loaded data into a variable named trainingData
Sets the colormap for plotting
Take the 1234th row of the loaded matrix, convert it into a 28-by-28 matrix, and store it in the variable x. So for example, on a smaller scale, [5 6 7 8] is converted to the matrix [5 7; 6 8] if you want to reshape that matrix to 2-by-2.
Reverse the column order of x and put that in y. So the last column becomes the first, second-last becomes second, etc.
This is a checkerboard plot of the values contained in y.
Edited to include more detail on lines 5 and 6:
The reshape line assumes that there is a row with number 1234, and that there are 784 (28*28) elements in that row. It takes that row, and makes a 28x28 matrix out of it, by taking the first 28 elements, making them into the first column of the new matrix, then taking the next 28 elements, making them the second column, and so on 26 more times. The final matrix is names x.
For the y line, like I said, it just reverses the columns of x, it puts the last column first, the second-last column second, and so on until the first column of the x is put as the last column of y.