How can I put the outputs of for loop into a matrix?
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Eray Bozoglu
el 30 de Nov. de 2020
Comentada: Eray Bozoglu
el 1 de Dic. de 2020
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 comentarios
Rik
el 30 de Nov. de 2020
You are still overwriting a in every iteration.
Did you do a basic Matlab tutorial?
Respuesta aceptada
John D'Errico
el 30 de Nov. de 2020
Editada: John D'Errico
el 30 de Nov. de 2020
First, don't use loops at all. For example, with n==3...
n = 3;
ind = 1:n;
a = ind.'*5/n + ind*8/n
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!