Array indexing, matrix indexing
Información
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Mostrar comentarios más antiguos
n=6;
h(:,:,1) = [0 1 2 1 2 3;
1 0 1 1 2 2;
2 1 0 2 1 1;
1 1 2 0 1 2;
2 2 1 1 0 1;
3 2 1 2 1 0];
h(:,:,2) = [0 2 3 2 3 4;
2 0 3 2 3 3;
3 3 0 3 2 2;
2 2 3 0 3 3;
3 3 2 3 0 2;
4 3 2 3 2 0];
for i = 1:n
for j = 1:n
if i ==n && j == n
fprintf('%d %d %d %d;\n', i, j, h(i,j,1),h(i,j,2));
else
fprintf('%d %d %d %d\n', i, j, h(i,j,1),h(i,j,2));
end
end
end
it give me the result like
1 1 0 0
1 2 1 2
1 3 2 3
1 4 1 2
1 5 2 3
1 6 3 4
2 1 1 2
2 2 0 0
2 3 1 3
.....
6 6 0 0;
..........................
i want to get expected result like
1 1 1
1 2 1
1 3 1
-----
6 6 1
1 1 2
1 2 2
1 3 2
----
2 1 2
2 2 2
----
6 6 2
the actual results print the value of i, j and h1(i,j) and h2(i,j) but actually i dont want to print the value of h1,h2 with respect to i, j but i want to print the results i,j and the index of h. Kindly guide me in this regards,
thank you
Respuesta aceptada
Más respuestas (2)
Andrey Kiselnikov
el 11 de Sept. de 2019
0 votos
Hi, it looks like you are still writing code on something like c or pascal using MATLAB syntax. First of all, you should change your mind, MATLAB was designed for matrix manipulations and you don't need to use nested cycles!
Good reference for this theme: https://www.mathworks.com/help/matlab/math/basic-matrix-operations.html
Good set of beginners exercises: https://www.mathworks.com/matlabcentral/cody/problems?sort=&term=group%3A%22Matrix+Manipulation+I%22
1 comentario
Irfanullah Khan
el 11 de Sept. de 2019
Hi, not sure why you are using the if condition as the statements are same in if and else block..
And use one more loop to get the dim of h if you want to do it in same manner : hope this will help you
n=6;
h(:,:,1) = [0 1 2 1 2 3;
1 0 1 1 2 2;
2 1 0 2 1 1;
1 1 2 0 1 2;
2 2 1 1 0 1;
3 2 1 2 1 0];
h(:,:,2) = [0 2 3 2 3 4;
2 0 3 2 3 3;
3 3 0 3 2 2;
2 2 3 0 3 3;
3 3 2 3 0 2;
4 3 2 3 2 0];
for dim = 1:size(h,3)
for i = 1:n
for j = 1:n
fprintf('%d %d %d \n', i, j, dim);
end
end
end
La pregunta está cerrada.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!