Assistance with creating multidimensional matrices

2 vues (au cours des 30 derniers jours)
Aaron
Aaron le 11 Juil 2012
I have created a program shown below:
Rows = input('Enter the number of rows in the matrix: '); Columns = input('Enter the number of columns in the matrix: '); for i = 1:Rows for j = 1:Columns fprintf('Enter A(%0.0f,%0.0f):',i,j); A(i,j) = input(' '); end end display(A)
I want to be able to run this program using different matrix dimensions, but when I run a 1x8 matrix, for example, and then try to run 8x1 matrix afterwards, I get an 8x8 matrix that has a bunch of zeros, which I don't want. I've noticed that the workspace saves the initial matrix and since. Am I able to correct this in my program or do I just have to clear the workspace every time I run this program?

Réponse acceptée

Ryan
Ryan le 11 Juil 2012
Modifié(e) : Ryan le 11 Juil 2012
I would pre-allocate A before the for loop by using
A = zeros(Rows,Cols); %Creates matrix of 0's
% This will also act to clear your previous value of A by replacing it with the
% zero matrix of the input size
% An alternative method would be to use 'clear A' before the code to empty the
% variable each run
If you are looking to save each run of A into a 3-dimensional array, then you'll need to save each matrix run in a cell array since each run results in a matrix of a different size.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by