Rakesh Kumar B.
asked 11/30/13Array in matlab
I'm trying to set up a matrix of variable length with two columns into which I can store the results of a for loop. The length will be determined by the number of iterations of the loop.
More
1 Expert Answer

Nathan C. answered 11/30/13
Tutor
5
(23)
Math and Science (K through College)
It is better to set the size of the matrix before the for loop. Typically, with a for loop, you know the number of iterations, even if it is a variable.
------------------
% where "n" is determined earlier in the script
results_matrix = zeros(n,2);
% creates a matrix filled with zeros of dimension n rows and 2 columns
for i_number_of_loop = 1:n
results_matrix(i_number_of_loop, :) =...
[i_number_of_loops, i_number_of_loops*n]
% this populates the matrix
% You'd insert your calculations here
end
--------------------------------------------
Rakesh Kumar B.
Thanks Nathan, for the answer. But actually I want to enter the matrix elements manually while then program is running.
Report
11/30/13

Nathan C.
Use the "input" function
http://www.mathworks.com/help/matlab/ref/input.html
You can use it to ask the user how many rows, then store the variable:
n = input('How many rows?');
Then have them enter each row from inside the for loop:
results_matrix(i_number_of_loop, :) = input('Enter the row using the notation [#,#]');
Of course, unless the for loop is necessary for the assignment, you could just have the user enter the entire matrix without a for loop:
results_matrix = input('Enter the entire matrix using the notation [#,#;#,#;#,#;...;#,#] where the commas separate the columns and the semicolons separate the rows');
Lastly, you can do a while loop instead of a for loop, not ask the user for the number of rows in advance, and just have them hit "enter" when they have no more rows to enter...
Report
11/30/13
Still looking for help? Get the right answer, fast.
Ask a question for free
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Find an Online Tutor Now
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Rakesh Kumar B.
11/30/13