Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

Creation of matrix from loop

1 vue (au cours des 30 derniers jours)
Renjith V Ravi
Renjith V Ravi le 17 Sep 2016
Clôturé : MATLAB Answer Bot le 20 Août 2021
The following is a code for creation of matrix using for loop
for r = 1:256;
for c=1:256;
m(r,c) = (r+c)^2;
end;
end;
disp(m)
In m(r,c) = (r+c)^2; Suppose, if there are two or more equations like (r+c)^2 and (2r-c)^2 and (r+3c) ,I want to get m(r1,c1)=(r+c)^2 and m(r2,c2)=(2r-c)^2 and m(r3,c2)=(r+3c) and again m(r4,c4)=(r+c)^2 and m(r5,c5)=(2r-c)^2 and ...... etc upto m(r256,c256).

Réponses (1)

Star Strider
Star Strider le 17 Sep 2016
I am not certain what you want to do, and you do not say what ‘(r2,c2)’ and the rest are, or what you want to do with them.
You can eliminate the loop with meshgrid:
r = 1:256;
c = 1:256;
[R,C] = meshgrid(r,c);
m = (R + C).^2;
figure(1)
meshc(R, C, m)
grid on
xlabel('\bf\itr')
ylabel('\bf\itc')
zlabel('\bf\itm')
  4 commentaires
Renjith V Ravi
Renjith V Ravi le 17 Sep 2016
Yes, But m = (R+C).^2 . I just want to merge r and c to form a matrix of size 256x256
Star Strider
Star Strider le 17 Sep 2016
My code does exactly that, without the loop.
Run my code and compare the figure it produces (in figure(1)) with the figure your code produces (in figure(2)):
for r = 1:256;
for c=1:256;
m(r,c) = (r+c)^2;
end;
end;
figure(2)
meshc(m)
grid on
The result is the same, the only difference being that my code is more efficient and easier to work with.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by