Read data rows one by one without specifying a range - matlab

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

Related

How to update image values by identifying unique locations in MATLAB?

I have a image matrix named final_img. I have image location matrix with rows and columns is given below
a =
1 1
1 2
2 1
2 2
3 1
3 2
1 1
2 2
and values of this locations are
b =
1
2
3
4
5
6
7
8
In above given locations, some are repeating eg: location [1 1] . I can identify unique locations by using following code
[uniquerow, ~, rowidx] = unique(a, 'rows');
noccurrences = accumarray(rowidx, 1);
I need to update unique image locations by summing image location values. Eg: location [1 1] is repeating twice and corresponding value in b are 1 and 7. So
final_img(1,1) should be 1+7=8;
How can I implement this algorithm in MATLAB without using for loop?
You can use the sparse function, which automatically adds all values corresponding to the same coordinates:
final_img = full(sparse(a(:,1), a(:,2), b));
This will create a matrix as small as possible according to the input.
If you want an ouput that is as small as possible with the resctriction that it be square:
M = max(a(:));
final_img = full(sparse(a(:,1), a(:,2), b, M, M));
If you want to specify size of the output:
M = 3;
N = 3;
final_img = full(sparse(a(:,1), a(:,2), b, M, N));
You were so incredibly close:
[final_coords, ~, rowidx] = unique(a, 'rows');
final_vals = accumarray(rowidx, b);
Then to get it to image form:
% empty matrix with size of your image
final_img = zeros(max(final_coords,[],1));
% get linear indexes from coordinates
ind = sub2ind(size(final_img), final_coords(:,1), final_coords(:,2));
% fill image
final_img(ind) = final_vals;

Matlab matrix accessing columns

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);

Replacing elements in a base matrix by squared permutation submatrices

I have a sparse parity check matrix (consisting of ones and zeros) and I would need to replace each nonzero element (ones) from it by PM: a squared permutation matrix of dimension N (being N generally a large integer). In the case of the zero elements, these would be replaced by squared null matrices of the same dimension.
Let me share with you which the current state of my code is:
This is the base matrix in which I would like to replace its ones by permutation matrices:
B = zeros((L + ms) * dc, L * dv);
for i = 1 : 1 : L
for j = 1 : 1 : dv
B(dc*(i-1)+1 : dc*(ms+i), j+dv*(i-1)) = ones(dc*(ms+1), 1);
end
end
I have been told a way for doing so by using 'cell' objects, this is, initializing H as an array of empty cells that would contain the corresponding submatrices:
H=repmat({{}},size(B));
Mc = 500 % Dimension of the permutation matrix
MP=randi([1,5],Mc,Mc); % Definition of one permutation matrix
% It would be desirable that the permutation matrix is different for each replacement
[H{B==0}]=deal(zeros(Mp));
[H{B==1}]=deal(MP);
But there's one problem coming up -that I would need this matrix to be used as a parameter of a following function and it would be very much desirable that it were a simple matrix of ones and zeros (as I am not very familiar with 'cell' structures... however, as you can see, Mc is such a big integer that I don't know if that would be possible to be handled.
Do you have any other way of doing so to have a raw matrix of dimensions (L*ms)dcMc, LdvMc as output?
These are some parameters that could be used to have a try:
ms = 2;
Mc = 600; % any number (specially big ones) could serve for this purpose
dc = 3;
dv = 4;
L = 15;
Many thanks in advance for your attention, and may you have a nice day.
This is how it can be done with cells:
B = Randi([0,1], m, n); % m*n array of 1s and 0s
H = cell(size(B)); % Define cell array
Mc = 500; % Size of replacement matrices
MP = randi([1,5], Mc, Mc); % Permutation matrix
H(B==0) = {zeros(Mc, Mc)}; % Set elements of H where B==0 to matrix of zeros
H(B==1) = {MP}; % Set elements of H where B==1 to permutation matrix
% Convert to matrix
Hmat = cell2mat(H); % Hmat = Mc*m row by Mc*n column matrix
Each cell element holds a matrix of size Mc*Mc, at the end this can be converted to one large matrix. Take care which sorts of brackets you use with cells, the parentheses () are for logical indexing, whilst the curly braces {} are for assigning the sub-matrixes as cell elements.
Example:
B = [1 0; 1 1];
MP = [1 2; 3 4];
H(B==0) = {zeros(2, 2)};
H(B==1) = {MP};
Hmat = cell2mat(H);
% >> Hmat = [1 2 0 0
% 3 4 0 0
% 1 2 1 2
% 3 4 3 4];
If you want the replacement matrix MP to change, you will have to do this in a loop, changing MP on each iteration and using it to replace one element of H.

Matlab: How to read data into a matrix

I have a data file matrix.txt, it has three columns. The first column stores the row index, the second column stores the column index, the third column stores the value. How do I read these into a matrix called mat. To be explicit, suppose our mat is a n*n square matrix, let n=2 for instance. In the text file, it has:
0 0 10
1 1 -10
The element in mat not specified is 0. Thus mat is supposed to be:
mat = 10 0
0 -10
How do I achieve this?
This should work for the generic 2-D case.
% Read in matrix specification
fID = fopen('matrix.txt');
tmp = fscanf(fID, '%u%u%f', [3 inf])';
fclose(fID);
% Use the maximum row and column subscripts to obtain the matrix size
tmp(:, 1:2) = tmp(:, 1:2) + 1; % MATLAB doesn't use 0-based indexing
matsize = [max(tmp(:,1)), max(tmp(:,2))];
% Convert subscripts to linear indices
lidx = sub2ind(matsize, tmp(:,1), tmp(:,2));
mat = zeros(matsize); % Initialize matrix
mat(lidx) = tmp(:,3); % Assign data
Using a sample matrix.txt:
0 0 10
1 1 -10
1 2 20
We receive:
>> mat
mat =
10 0 0
0 -10 20
Since in MATLAB, indices begin with 1 (not zero), we should add 1 to our indices in code.
r and c stand for row and column.
Alsom and n is for m by n zero matrix
A = importdata('matrix.txt');
r = A(:, 1)';
c = A(:, 2)';
m = max(r);
n = max(c);
B = zeros(m + 1, n + 1);
for k = 1:size(A,1);
B(r(k) + 1, c(k) + 1) = A(k, 3);
end
Result:
B =
10 0
0 -10
I see I am too slow, but I decided post my answer anyway...
I initialized matrix A as a vector, and used reshape:
%Load all file to matrix at once
%You may consider using fopen and fscanf, in case Matrix.txt is not ordered perfectly.
row_column_val = load('Matrix.txt', '-ascii');
R = row_column_val(:, 1) + 1; %Get vector of row indexes (add 1 - convert to Matalb indeces).
C = row_column_val(:, 2) + 1; %Get vector of column indexes (add 1 - convert to Matalb indeces).
V = row_column_val(:, 3); %Get vector of values.
nrows = max(R); %Number of rows in matrix.
ncols = max(C); %Number of columns in matrix.
A = zeros(nrows*ncols, 1); %Initialize A as a vector instead of a matrix (length of A is nrows*ncols).
%Put value v in place c*ncols + r for all elements of V, C and R.
%The formula is used for column major matrix (Matlab stored matrices in column major format).
A((C-1)*nrows + R) = V;
A = reshape(A, [nrows, ncols]);

How to index a matrix with the column maxima of other matrix

I have 2 matrices A and B.
I find the max values in the columns of A, and keep their indices in I. So far so good.
Now, I need to choose those arrays of B with the same index as stored in I. I don't know how to do this.
See below:
A = [1,2,3; 0,8,9]
B = [0,1,2; 4,2,3]
[~,I] = max(A)
h = B(I)
I need to get these values of B:
h = [0 2 3]
But the code results in a different one. How can I fix it?
A =
1 2 3
0 8 9
B =
0 1 2
4 2 3
I =
1 2 2
h =
0 4 4
Thanks in advance
The max function how you used it works like
If A is a matrix, then max(A) is a row vector containing the maximum value of each column.
so M = max(A) is equivalent to M = max(A,[],1). But rather use the third input if you're not sure.
If you use max to find the maxima in the columns of the matrix, it returns the row indices. The column indices are for your case simply 1:size(A,2) = [1 2 3].
Now you need to convert your row and column indices to linear indices with sub2ind:
%// data
A = [1,2,3; 0,8,9]
B = [0,1,2; 4,2,3]
%// find maxima of each column in A
[~, I] = max( A, [], 1 ) %// returns row indices
%// get linear indices for both, row indices and column indices
I = sub2ind( size(A), I, 1:size(A,2) )
%// index B
h = B(I)
returns:
h =
0 2 3