Reshape error on Matlab I can't figure out? - matlab

Trying to add a row and column of zeroes to a user inputted matrices, can't fin any way past the reshape error
n = input ('Please Enter Desired Number of Rows:');
disp (''); % User prompted to enter the desied rows for the matrices.
m = input ('Please Enter Desired Number of Columns:');
disp (''); % User prompted to enter the desired columns for the matrices.
for x = 1:n
for y = 1:m
p (x,y) = input ('Enter Matrice Values:');
end
end
p = reshape (p, n, m);
% Adding Row of Zeros
a = zeros (1,m+1)
% Adding Column of Zeros
b= zeros (n,1)
Output_Matrix = [p b; a]

You don't need to reshape, get the size of p that was input by the user using [m, n] = size(p) and create Output_Matrix that's one row and one column bigger. Set the first m rows and n columns to p. Finally don't forget to preallocate any arrays before accessing them.
% User prompted to enter the desied rows for the matrices.
m = input('Please Enter Desired Number of Rows: '); disp ('')
% User prompted to enter the desired columns for the matrices.
n = input('Please Enter Desired Number of Columns: '); disp ('')
p = zeros(m,n);
for x = 1:m
for y = 1:n
p(x,y) = input('Enter Matrice Values: ');
end
end
[m, n] = size(p);
Output_Matrix = zeros(m+1,n+1);
Output_Matrix(1:end-1,1:end-1) = p;
Output_Matrix =
1 2 3 0
4 5 6 0
7 8 9 0
0 0 0 0

If you have a p matrix from some previous code and you want to expand it, you can simply do this to get that extra row and column of 0's appended:
% p is pre-existing from some other code
p(end+1,end+1) = 0; % this appends extra row and column of 0's
But if you are building the p from scratch and know the desired size ahead of time, then Chris's comment about pre-allocating p to zeros(m+1,n+1) is probably the way to go.

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

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

Input space separated matrix in matlab of dim (m X n)

I am just a beginner using MatLab. I wanted to add 2 matrices in which user inputs dimension of matrix and then inputs values.
Values are inserted element by element.
I want user to input values row-wise, i.e., for a 2x3 matrix, user should input 2 lines, each line with 3 space separated integer values.
m = input('Enter no. of rows ');
n = input('Enter no. of columns ');
A = zeros(m, n);
B = zeros(m, n);
C = zeros(m, n);
disp('Enter elements in matrix A ');
for i=1 : m
for j=1 : n
A(i,j) = input('\');
end
end
disp('Enter elements in matrix B ');
for i = 1 : m
for j = 1 : n
B(i, j) = input('\');
C(i, j) = A(i, j) + B(i, j);
end
end
clc;
disp('Matrix A is');
A
disp('Matrix B is');
B
disp('Matrix A + B is');
C
How shall i do that?
You could do it using:
for j=1 : n
A(:,j) = input('\');
end
Then the user has to enter a row like [1,2,3,4]
My recommendation is to ask for the full matrix at once. This way the user can enter a variable name which contains the intended function.

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