How can I put the outputs of for loop into a matrix?

9 次查看(过去 30 天)
Hey i am new to matlab and need help with storing answer of my for loop into a matrix can anyone help ?
my aim is having (n x n) matrix. thanks a lot
n=input('please enter n>');
for j=1:n
for i=1:n
a=(5*(i/n))+(8*(j/n));
end
end
  3 个评论
Eray Bozoglu
Eray Bozoglu 2020-11-30
edited the post im trying to have (n x n) matrix. with the current code if i plug 2 i can have 4 out put. such as
a b c d
i want to have them stored as [a b ; c d]
so for bigger n i can have better overview and use it in another script with defining it as a matrix.
Rik
Rik 2020-11-30
You are still overwriting a in every iteration.
Did you do a basic Matlab tutorial?

请先登录,再进行评论。

采纳的回答

John D'Errico
John D'Errico 2020-11-30
编辑:John D'Errico 2020-11-30
First, don't use loops at all. For example, with n==3...
n = 3;
ind = 1:n;
a = ind.'*5/n + ind*8/n
a = 3×3
4.3333 7.0000 9.6667 6.0000 8.6667 11.3333 7.6667 10.3333 13.0000
Since this is probably homework, and a loop is required, while I tend not to do homework assignments, you came pretty close. You made only two mistakes. First, you did not preallocate a, which is important for speed, but not crucial. It would still run without that line. Second, you are stuffing the elements as created into a(i,j). So you need to write it that way.
n = 3;
a = zeros(n); % preallocate arrays
for i = 1:n
for j = 1:n
a(i,j) = (5*(i/n))+(8*(j/n));
end
end
a
a = 3×3
4.3333 7.0000 9.6667 6.0000 8.6667 11.3333 7.6667 10.3333 13.0000

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by