How to extract columns with a for loop? - matlab

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

Related

How to compute the outer product of two binary vectors

I am generating a random binary matrix with a specific number of ones in each row. Now, I want to take each row in the matrix and multiply it by its transpose (i.e row1'*row1).
So, I am using row1=rnd_mat(1,:) to get the first row. However, in the multiplication step I get this error
"Both logical inputs must be scalar. To compute elementwise TIMES, use TIMES (.*) instead."
Knowing that I don't want to compute element-wise, I want to generate a matrix using the outer product. I tried to write row1 manually using [0 0 1 ...], and tried to find the outer product. I managed to get the matrix I wanted.
So, does anyone have some ideas on how I can do this?
Matrix multiplication of logical matrices or vectors is not supported in MATLAB. That is the reason why you are getting that error. You need to convert your matrix into double or another valid numeric input before attempting to do that operation. Therefore, do something like this:
rnd_mat = double(rnd_mat); %// Cast to double
row1 = rnd_mat(1,:);
result = row1.'*row1;
What you are essentially computing is the outer product of two vectors. If you want to avoid casting to double, consider using bsxfun to do the job for you instead:
result = bsxfun(#times, row1.', row1);
This way, you don't need to cast your matrix before doing the outer product. Remember, the outer product of two vectors is simply an element-wise multiplication of two matrices where one matrix is consists of a row vector where each row is a copy of the row vector while the other matrix is a column vector, where each column is a copy of the column vector.
bsxfun automatically broadcasts each row vector and column vector so that we produce two matrices of compatible dimensions, and performs an element by element multiplication, thus producing the outer product.

How to change the value of a random subset of elements in a matrix without using a loop?

I'm currently attempting to select a subset of 0's in a very large matrix (about 400x300 elements) and change their value to 1. I am able to do this, but it requires using a loop where each instance it selects the next value in a randperm vector. In other words, 50% of the 0's in the matrix are randomly selected, one-at-a-time, and changed to 1:
z=1;
for z=1:(.5*numberofzeroes)
A(zeroposition(rpnumberofzeroes(z),1),zeroposition(rpnumberofzeroes(z),2))=1;
z=z+1;
end
Where 'A' is the matrix, 'zeroposition' is a 2-column-wide matrix with the positions of the 0's in the matrix (the "coordinates" if you like), and 'rpnumberofzeros' is a randperm vector from 1 to the number of zeroes in the matrix.
So for example, for z=20, the code might be something like this:
A(3557,2684)=1;
...so that the 0 which appears in this location within A will now be a 1.
It performs this loop thousands of times, because .5*numberofzeroes is a very big number. This inevitably takes a long time, so my question is can this be done without using a loop? Or at least, in some way that takes less processing resources/time?
As I said, the only thing that needs to be done is an entirely random selection of 50% (or whatever proportion) of the 0's changed to 1.
Thanks in advance for the help, and let me know if I can clear anything up! I'm new here, so apologies in advance if I've made any faux pa's.
That's very easy. I'd like to introduce you to my friend sub2ind. sub2ind allows you to take row and column coordinates of a matrix and convert them into linear column-major indices so that you can access multiple values in a matrix simultaneously in a single call. As such, the equivalent code you want is:
%// First access the values in rpnumberofzeroes
vals = rpnumberofzeroes(1:0.5*numberofzeroes, :);
%// Now, use the columns of these to determine which rows and columns we want
%// to access A
rows = zeroposition(vals(:,1), 1);
cols = zeroposition(vals(:,2), 2);
%// Get linear indices via sub2ind
ind1 = sub2ind(size(A), rows, cols);
%// Now set these locations to 1
A(ind1) = 1;
The first statement gets the first half of your matrix of coordinates stored in rpnumberofzeroes. The first column is the row coordinates, the second column is the column coordinates. Notice that in your code, you wish to use the values in zeroposition to access the locations in A. As such, extract out the corresponding rows and columns from rpnumberofzeroes to figure out the right rows and columns from zeroposition. Once that's done, we wish to use these new rows and columns from zeroposition and index into A. sub2ind requires three inputs - the size of the matrix you are trying to access... so in our case, that's A, the row coordinates and the column coordinates. The output is a set of column major indices that are computed for each row and column pair.
The last piece of the puzzle is to use these to index into A and set the locations to 1.
This can be accomplished with linear indexing as well:
% find linear position of all zeros in matrix
ix=find(abs(A)<eps);
% set one half of those, selected at random, to one.
A(ix(randperm(round(numel(ix)*.5)))=1;

MATLAB: why transpose single dimension array

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.

matlab: populating a sparse matrix with addition

preface: As the matlab guiderules state, Usually, when one wants to efficiently populate a sparse matrix in matlab, he should create a vector of indexes into the matrix and a vector of values he wants to assign, and then concentrate all the assignments into one atomic operation, so as to allow matlab to "prepare" the matrix in advance and optimize the assignment speed. A simple example:
A=sparse([]);
inds=some_index_generating_method();
vals=some_value_generating_method();
A(inds)=vals;
My question: what can I do in the case where inds contain overlapping indexes, i.e inds=[4 17 8 17 9] where 17 repeats twice.
In this case, what I would want to happen is that the matrix would be assigned the addition of all the values that are mapped to the same index, i.e for the previous example
A(17)=vals(2)+vals(4) %as inds(2)==inds(4)
Is there any straightforward and, most importantly, fast way to achieve this? I have no way of generating the indexes and values in a "smarter" way.
This might help:
S = sparse(i,j,s,m,n,nzmax) uses vectors i, j, and s to generate an m-by-n sparse matrix such that S(i(k),j(k)) = s(k), with space allocated for nzmax nonzeros. Vectors i, j, and s are all the same length. Any elements of s that are zero are ignored, along with the corresponding values of i and j. Any elements of s that have duplicate values of i and j are added together.
See more at MATLAB documentation for sparse function

remove columns of zeros for regstats function

I'm performing linear regression analyses (y=xb, solving for b with a given [nx1] vector y and [nxm] matrix x) on a pretty large set of data, using the regstats() function the Matlab statistics toolbox and looping through a series of matrix/vector pairs. The problem is that regstats returns NaN if there are columns of all zeros, because it can't perform the regression. There are columns of zeros in all of my x-matrices, but they do not always appear in the same column numbers. Since each column in my x-matrices represents a real-world variable, I can't just simply remove columns of zeros and run the regression. I need to remove the zeros, remember which columns have been removed, run the regression, and then incorporate 0 values into the b vector result in the appropriate places. That way all of my results represent the same number of variables in the same order, with zeros in the places where that particular variable was not included in the regression. I did this manually with a small set of test data, but now I need to run it for about 800 regression pairs so I need some way to automate searching for and replacing the zero columns.
IZEROS = find(all(M==0));
IZEROS will be a list of the indices of the columns that have all zeros.
allzero = all(x == 0, 1);
goodcols = find(~allzero);
b = zeros(m,1);
b(goodcols) = % solution to problem, taking into account only goodcols