Info
此问题已关闭。 请重新打开它进行编辑或回答。
Array indexing, matrix indexing
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Bob Thompson
2019-9-11
Personally, I don't think the loops are necessary. It's not much cleaner looking than the loops, but I suspect it will run more quickly. Because you're just looking to produce index values, then you really don't need to involve h at all during this stage.
p = 1:n;
p = repmat(p,n,1);
p = reshape(p,[],1);
q = 1:n;
q = repmat(q,1,n);
p = [p q'];
p = repmat(p,2,1);
p(:,3) = [repmat(1,n^2,1);repmat(2,n^2,1)];
fprintf('%d %d %d\n',p');
2 个评论
Bob Thompson
2019-9-11
Just to clarify, are you asking on a MATLAB forum for a non-MATLAB code question? I don't know that you're going to get very good answers that way.
I am not familiar with the GLPK language or syntax, but if you want a loop version to create the matrices I indicated before then you can use something like the following:
for i = 1:2
for j = 1:n
for k = 1:n
fprintf('%d %d %d\n', j , k , i);
end
end
end
更多回答(2 个)
Andrey Kiselnikov
2019-9-11
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 个评论
Amit
2019-9-11
编辑:Amit
2019-9-11
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
0 个评论
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!