MATLAB: why transpose single dimension array - matlab

I have the following Matlab code snippet that I'm having to translate to VBScript. However, I'm not understanding why the last line is even necessary.
clear i
for i = 1:numb_days
doy(i) = floor(dt_daily(i) - datenum(2012,12,31,0,0,0));
end
doy = doy';
Looking over the rest of the code, this happens in a lot of other places where there are single dimension arrays (?) being transposed in place. I'm a newbie when it comes to both these languages, as well as posting a question on Stack, as I'm a sleuth when it comes to finding answers, just not in this case. Thanks in advance.

All "arrays" in MATLAB have at least two dimensions, and can be treated as having any number of dimensions you wish. The transpose operator here is converting between a row (size [1 N] array) and a column (size [N 1] array). This can be significant when it comes to either concatenating the arrays, or performing other operations.
Conceptually, the dimension vector of a MATLAB array has as many trailing 1s as is required to perform an operation. This means that you can index any MATLAB array with any number of subscripts, providing you don't exceed the bounds, like so:
x = magic(4); % 4-by-4 square matrix
x(2,3,1,1,1) % pick an element
One final note: the ' operator is the complex-conjugate transpose CTRANSPOSE. The .' operator is the ordinary TRANSPOSE operator.

Related

How to extract columns with a for loop?

Question
If there is a matrix of MxN, how can extract all of the data based in the columns?
Im interesting to pass each column to a function and to be plotted.
if A(:) is used all the matrix is merged into a single column, (I remember this command is intended for that) but this does not serve to me.
Matlab arrays use the indexing, partOfArray = array(rows, columns). The variables rows and columns can be a vector (including a scalar, which is a vector of length 1) or : which is effectively interpreted by Matlab as meaning 'all' (e.g. array(:,columns) would be all rows of the selected columns).
Alternatively, Matlab also allows linear indexing, in which array(aNumber) counts in order from array(1,1) first by rows, then by columns. e.g. if array is 2x4, array(5) is equivalent to array(2,1). When you call A(:) Matlab interprets that as using linear indexing to access all elements in the array, hence merging the matrix into a single column.
To access each column vector in a for loop, in this case printing it out, use:
A = magic(4)
numColumnsInA = size(A,2);
for i=1:numColumnsInA
disp(A(:,i))
end
You can find more information about indexing in Matlab here: Array Indexing

What is the colon operator doing here?

What are these lines of code doing?
x0 = rand(n,2)
x0(:,1)=W*x0(:,1)
x0(:,2)=H*x0(:,2)
x0=x0(:)
Is this just one big column vector?
I'd encourage you to take a MATLAB Tutorial as indexing arrays is a fundamental skill. Also see Basic Concepts in MATLAB. Line-by-line descriptions are below to get you started.
What are these lines of code doing?
Let's take this line by line.
1. This line uses rand() to generate an n x 2 matrix of uniform random numbers (~U(0,1)).
x0 = rand(n,2) % Generate nx2 matrix of U(0,1) random numbers
2. Multiply the first column by W
In this case, x0(:,1) means take all rows of x0 (the colon in the first argument) and the 1st column (the 1). Here, the * operator indicates W is a scalar or an appropriately sized array for feasible matrix multiplication (my guess is a scalar). The notation .* can be used for element-by-element multiplication; see here and here for more details.
x0(:,1)=W*x0(:,1) % Multiply (all rows) 1st column by W
3. Multiply the first column by H.
Using similar logic as #2.
x0(:,2)=H*x0(:,2) % Multiply (all rows) 2nd column by H
4. Force column
The x0(:) takes the array x0 and forces all elements into a single column.
From the documentation for colon:
A(:) reshapes all elements of A into a single column vector. This has
no effect if A is already a column vector.
A related operation is forcing a row vector by combining this with the transpose operator.
For example, try the following: x0(:).'
x0 = x0(:) % Force Column
x0 = x0(:).' % Force Row
Related Posts:
What is Matlab's colon operator called?
How does MATLAB's colon operator work?
Combination of colon-operations in MATLAB

Purpose of matrix length

Matlab defines the matrix function length to return
Length of largest array dimension
What is an example of a use of knowing the largest dimension? Knowing number of rows or columns has obvious uses... but I don't know why someone would want the largest dimension regardless of whether it is rows or cols.
Thank You
In fact, most of my code wants to do things exactly once for each row, for each column or for each element.
Therefore, I typically use one of these
size(M,1)
size(M,2)
numel(V)
In particular do not depend on length to match the number of elements in a vector!
The only real convenience that I found {in older versions of matlab} for length is if I need a repeat statement rather than a while. Then it is convenient that length of vectors usually returns at least one.
Some other uses that I had for length:
A quick rough check whether something is big.
Making something square as mentioned by #Mike
This question addresses a good point and I have seen programs fail because of applying the length command on matrices (for looping). Especially when one expects to get size(M, n) because the n-th dimension should be the largest. In total, I can not see an advantage of allowing length to be applied on matrices, in fact I only see risks from probably unexpected behavior.
If I want to know the largest dimension of any matrix, I would prefer to be more explicit and use max(size(M)), which also should be much clearer for anyone reading this code.
I am not sure, whether the following example should be in this answer, but It somehow addresses the same point.
It is also useful to be explicit with dimension, when averaging over matrices. Consider the case, where you always want to average over the first dimension, i.e. over the columns of a matrix. As long as your matrix is of size n x m, where n is greater than 1, you do not have to care about specifying a dimension. But for unforseen cases, where your matrix happens to be a row-vector, things get messy:
%// good case, where num of rows is 2 or greater
size(mean(rand(2, 4), 1)) %// [1, 4]
size(mean(rand(2, 4))) %// [1, 4]
%// bad case, where num of rows is 1
size(mean(rand(1, 4), 1)) %// [1, 4]
size(mean(rand(1, 4))) %// [1, 1], returns the average of that row
If you want to create a square matrix B that can contain the input matrix A which is non-square, you can take the latter's length and use it to initialize the matrix B with zeros where the rows and columns would be of A's length, then copy the input matrix into the new zeroed matrix.
Another example - the one I use most - is when working with vectors. There it is very convenient to work with length instead of size(vec,1) or size(vec,2) as it doesn't matter if it is a row or a column vector.
As #Dennis Jaheruddin pointed out, length gave wrong results for empty vectors in some versions of MATLAB. Using numel instead of length might therefore be convenient for better backward compatibility. The readibility of the code is almost the same IMHO.
This question compares length and numel and their performance, and comes to the result that they perform similarly up to 100k elements in a vector. With more than 100k elements, numel appears to be faster. I tried to verify this (with MATLAB R2014a) and came to the following results:
Here, length is a bit slower, but as it is in the range of micro seconds, I guess it won't be a real difference in speed.

MTIMES is not fully supported for integer classes. At least one input must be scalar

I'm trying to implement a 1 dimensional DFT without using Matlab built-in functions such as fft(). This is my code
function [Xk] = dft1(xn)
N=length(xn);
n = 0:1:N-1; % row vector for n
k = 0:1:N-1; % row vecor for k
WN = exp(-1j*2*pi/N); % Twiddle factor (w)
nk = n'*k; % creates a N by N matrix of nk values
WNnk = WN .^ nk; % DFT matrix
Xk = (WNnk*xn );
when i run the code after using the following commands:
I = imread('sample.jpg')
R = dft1(I)
I get this particular error:
Error using *
MTIMES is not fully supported for
integer classes. At least one input
must be scalar.
To compute elementwise TIMES, use
TIMES (.*) instead.
Can someone please help me to figure out how to solve this problem
Note: I am still in the very beginning level of learning Matlab
thank you very much
You just need to cast the data to double, then run your code again. Basically what the error is saying is that you are trying to mix classes of data together when applying a matrix multiplication between two variable. Specifically, the numerical vectors and matrices you define in dft1 are all of a double type, yet your image is probably of type uint8 when you read this in through imread. This is why you're getting that integer error because uint8 is an integer class and you are trying to perform matrix multiplication with this data type with those of a double data type. Bear in mind that you can mix data types, so long as one number is a single number / scalar. This is also what the error is alluding to. Matrix multiplication of varaibles that are not floating point (double, single) is not supported in MATLAB so you need to make sure that your image data and your DFT matrices are the same type before applying your algorithm.
As such, simply do:
I = imread('sample.jpg');
R = dft1(double(I));
Minor Note
This code is quite clever, and it (by default) applies the 1D DFT to all columns of your image. The output will be a matrix of the same size as I where each column is the 1D DFT result of each column from I.
This is something to think about, but should you want to apply this to all rows of your image, you would simply transpose I before it goes into dft1 so that the rows become columns and you can operate on these new "columns". Once you're done, you simply have to transpose the result back so that you'll get your output from dft1 shaped such that the results are applied on a per row basis. Therefore:
I = imread('sample.jpg');
R = dft1(double(I.')).';
Hope this helps! Good luck!

Matlab - Matrix Division by Zero - Zeros and NaNs

I am trying to convert a precision matrix sigmaT to a covariance matrix. I've tried two approaches:
covMat = zeros(size(sigmaT));
for i=1:t
covMat(:, :, i) = eye(D)/sigmaT(:,:,i);
end
and
covMat = bsxfun(#rdivide, eye(D), sigmaT);
Some of the elements in sigmaT are zero, so division by zero occurs. The first loop-based solution keeps the elements where division by 0 occurs as 0, the second approach sets the elements to NaN.
My questions would be: why do they behave differently and how can I change the second one-line approach to behave as the loop-based approach? I believe the latter solution should be significantly faster on large matrices.
Your loop based approach is performing matrix division, that is the result for each iteration is the matrix inverse of sigmaT(:,:,i). You can adjust the loop to perform per-element math by using the ./ operator (instead of /).
Your bsxfun based approach is performing per-element division, that is each individual element is inverted. There is no way to use bsxfun to perform a matrix operation on each 2D matrix contained in a 3D array.
These answers are very different. You should use whatever approach is appropriate for your problem. The performance difference between the two is probably relatively small.