Home > Enterprise >  Reshape error on Matlab I can't figure out?
Reshape error on Matlab I can't figure out?

Time:06-03

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]

CodePudding user response:

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

CodePudding user response:

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