Matlab matrix accessing columns - matlab

Can someone explain what is happening here?
I know that Y(:,1) is the first column of values in Y.
But what does Y(p,1) mean?
Matlab noob
Y = load('testFile.txt'); %Load file
p = randperm(length(Y)); %List of random numbers between 0 and Y size
Y(:,1) = Y(p,1);
Y(:,2) = Y(p,2);
Y(:,3) = Y(p,4);

Y = load('testFile.txt'); %Load file
% create a mapping to shuffle the rows of Y.
% This assumes more rows than columns in Y, otherwise the code doesn't make sense.
% This is because length(Y) returns the length of the largest dimension.
% A more robust implementation would use size(Y,1) rather than length(Y).
p = randperm(length(Y)); %List of random numbers between 0 and Y size
% Rearrange the rows of column 1 based on the shuffled order
Y(:,1) = Y(p,1);
% Rearrange the rows of column 2 based on the shuffled order
Y(:,2) = Y(p,2);
% Set the third column to the shuffled fourth column.
Y(:,3) = Y(p,4);

Related

Read data rows one by one without specifying a range

Can I read each record of a dataset without specifying a range, i.e. not specifying for 1=1:n?
For example :
A = [4 2;
2 4;
2 3;
3 6;
4 4];
I want to read/get rows from A one by one, A(1,:) to A(5,:), and stop reading when the last record is found: A(5,:).
Thanks.
So you don't want to specify some maximum length?
To get the number of rows in a MATLAB matrix, you can use any of these methods:
n = size(A, 1); % Size in dimension 1 (rows)
% or
n = length(A); % Length of largest array dimension, so needs rows > columns
% or
n = numel(A(:,1)); % Gets number of elements (numel) in column 1 of A
Then loop like so
for k = 1:size(A,1)
temp = A(k, :); % Do something with row k
end

Print/Store each row in matrix - MATLAB

I have a 150 X 4 matrix and I wish to loop through the matrix length and print each of the rows out.
This is my attempted code:
X = xlsread('filename.csv');
J = X(:, [2:5]) % extracting rows 2 to 5 into a matrix
for i= 0:length(J)
Y = J(i,:); %loop through each row and store it in Y
end;
But I keep getting the following error:
Subscript indices must either be real positive integers or logicals.
Is my approach incorrect? What am I missing out here? I simply want to loop through each row and store it in a variable.
In MATLAB the indices start at 1 and not at 0, so you should do:
for i= 1:length(J)
Y = J(i,:); %loop through each row and store it in Y
end;
In addition, regarding the following line that you wrote:
J = X(:, [2:5]) % extracting rows 2 to 5 into a matrix
Note that you actually stored in J columns 2,3,4,5, of X and not rows 2,3,4,5.

Matlab d-dimensional multipication table?

I'm new to Matlab and I'm trying to solve a problem that involves creating a d dimensional multiplication table where each edge goes from 1 to n. The problem statement says that inputting d = 0 should return the number 1 and d = 1 should return a column vector with the elements 1 to n.
Ideally, I would just create a matrix of 1 to n along d dimensions and then iterate through for each element setting it equal to the product of the indices, but I don't know how to create the d dimensional matrix.
Can anyone help me with this problem?
You can create the table with repeated use of bsxfun. At each iteration, the vector 1,2,...,n is shifted to a new dimension and multiplied (with singleton expansion) by the previous result.
%// Data
d = 3;
n = 10;
%// Computations
vector = (1:n).'; %// first dimension: column vector
result = 1; %// initialization
for n = 1:d
result = bsxfun(#times, result, vector); %// new dimension
vector = shiftdim(vector,-1); %// shift to the next dimension
end

Generate every binary n x m matrix in matlab

I'd like to generate every boolean matrix in matlab as a 3-dimensional array.
For example:
mat(:,:,1) = [[1 0][0 1]]
mat(:,:,2) = [[1 1][0 1]]
...
My final goal is to generate every trinary matrix of a given size.
Keep in mind that I know that the number of matrices is exponential, but I'll use small numbers.
Not sure that the previous answer actually does what you want... With that method, I get multiple entries in array2D that are the same. Here is a vectorised and (I believe) correct solution:
clear all;
nRows = 2;
nCols = nRows; % Only works for square matrices
% Generate matrix of all binary numbers that fit in nCols
max2Pow = nCols;
maxNum = 2 ^ max2Pow - 1;
allBinCols = bsxfun(#bitand, (0:maxNum)', 2.^((max2Pow-1):-1:0)) > 0;
% Get the indices of the rows in this matrix required for each output
% binary matrix
N = size(allBinCols, 1);
A = repmat({1:N}, nCols, 1);
[B{1:nCols}] = ndgrid(A{:});
rowInds = reshape(cat(3, B{:}), [], nCols)';
% Get the appropriate rows and reshape to a 3D array of right size
nMats = size(rowInds, 2);
binMats = reshape(allBinCols(rowInds(:), :)', nRows, nCols, nMats)
Note that for anything other than small numbers of nRows you will run out of memory pretty quickly, because you're generating 2^(nRows*nRows) matrices of size nRows*nRows. ThatsAlottaNumbers.
Actually the answer is pretty straightforward. Each matrix being boolean, it can be indexed by the binary number obtained when reading all the values in any given order.
For a binary matrix: let n be the number of element in your matrix (n = rows * cols).
for d=0:(2^n-1)
%Convert binary to decimal string
str = dec2bin(d);
%Convert string to array
array1D = str - '0';
array1D = [array1D zeros(1, n-length(array1D))];
%Reshape
array2D(:,:,d+1) = reshape(array1D, rows, cols);
end
This can be very easily generalized to any base by changing dec2bin into dec2base and changing 2^n into (yourbase)^n.

Matlab - Generating random coordinates for a matrix

I need to create a list (of size n) of random, non-repeating set of coordinates on a matrix of predefined size.
Is there a fast way to generate this in Matlab?
My initial idea was to create a list of size n with permutations the size of (width x length) and to translate them back to Row and Col values, but it seems to me too much.
Thanks,
Guy
You can use randperm to generate a linear index, and convert it to [row,col] if needed using ind2sub.
x = rand(7,9);
n = 20;
ndx = randperm(numel(x), n);
[row,col] = ind2sub(size(x), ndx);
As long as n is less than the number of elements in the matrix this is simple:
% A is the matrix to be sampled
% N is the number of coordinate pairs you want
numInMat = numel(A);
% sample from 1:N without replacement
ind = randperm(numInMat, N);
% convert ind to Row,Col pairs
[r, c] = ind2sub( size(A), ind )
Your idea is a good one, although you don't even have to convert your linear indices back to row and col indices, you can do linear indexing directly into a 2D array.
idx = randperm(prod(size(data)))
where data is your matrix. This will generate a vector of random integers between 1 and prod(size(data)), i.e. one index for each element.
e.g.
n = 3;
data = magic(n);
idx = randperm(prod(size(data)));
reshape(data(idx), size(data)) %this gives you your randomly indexed data matrix back