How can I store a matrix without delete the previous one using a loop?

Hi, in my code I´m doing a loop in order to create a 2X4 matrix and the idea is allocate each matrix under the last one, but each time it runs the previous matrix is deleted. my look like this
for i=1:10
for j=1:10
nodo1=[i,j];
nodo2=[i+1,j];
nodo3=[i,j+1];
nodo4=[i+1,j+1];
punto_med=(nodo1+nodo2+nodo3+nodo4)/4;
distancia=sqrt((5-punto_med(1,1))^2+(5-punto_med(1,2))^2);
if distancia <=5
nodos= [nodo1; nodo2; nodo2; nodo3];
nodos_totales(:,:) = nodos
end
end
end
where nodos_totales don´t store all the matrix.
thenk if any one can help me.

 채택된 답변

Jan
Jan 2013년 1월 29일
편집: Jan 2013년 1월 29일
Use a 3D array:
c = 0;
for i=1:10
for j=1:10
...
if distancia <=5
c = c + 1;
nodos_totales(:, c) = [nodo1; nodo2; nodo2; nodo3]
end
Or a cell array:
nodos_totales{c} = [nodo1; nodo2; nodo2; nodo3]
Note: The SQRT is an expensive operation. Instead of comparing sqrt(x) <= 5 it is much cheaper to compare x < 25.
For this small problem of maximum size 10x10 a pre-allocation is not so important. But it is a good programming practice to pre-allocate in any case:
Before the code:
nodos_totales = zeros(4, 100)
and at the end:
nodos_totales = nodos_totales(:, 1:c);

추가 답변 (1개)

Juan Vaca
Juan Vaca 2013년 1월 29일

0 개 추천

Hi Jan, thank you very much for your answer it was very useful for solve that problem.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 1월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by