Array indexing, matrix indexing

1 view (last 30 days)
Irfanullah Khan on 11 Sep 2019
Closed: Stephen Cobeldick on 11 Sep 2019
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

Bob Thompson on 11 Sep 2019
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');
Bob Thompson on 11 Sep 2019
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

Andrey Kiselnikov on 11 Sep 2019
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!
Irfanullah Khan on 11 Sep 2019
yes, you are right. i am using GLPK to write the code for optimization problem. Kindly modify the above code as expecting result. thanking you

Amit on 11 Sep 2019
Edited: Amit on 11 Sep 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