How can I create a 10x4 matrix with a for loop?
Show older comments
I came across the following problem in my Matlab textbook: Write a loop that generates a column vector A with ten random numbers. Then create a 10 × 4 matrix having A as its fi rst column, with the remaining columns the product of the first column and the column number.
The solution they gave is the following:
for ind = 1:10;
A(ind) = rand;
end
for ind2 = 1:4;
B(1:10, ind2) = A*ind2;
end
However, although I understand each line of the code, I can't understand the logic behind the following:
1. How does the program know that 1:10 in the second for loop refers to vector A (indeed, when i run the code, the first column is vector A);
2. What sort of expression is the last one
B(1:10, ind2) = A*ind2;
i.e., shouldn't A*ind2 be in the parenthesis to indicate the other 3 columns? What does the "=" stand for here?
Also, I tried to solve it for quite a while and this is what I came up with:
A = rand(10,1);
for ii = 1:4;
ii;
x = A*ii;
B = horzcat(A,x,x,x)
end
The last command basically creates a 10x4 matrix, however, instead of creating 3 different x vectors, it just reapeats x 3 times.
Could you please tell me how to amend my code, so that it works?
Thanks a lot!! I appreciate greatly any help and comments
Silvi
Accepted Answer
More Answers (0)
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!