print 2d array using nested foor

4 次查看(过去 30 天)
Abdullah Afar
Abdullah Afar 2022-10-10
回答: Dyuman Joshi 2022-10-11
Hello, I want to print an array as follows
9 9 9 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8 8 8
7 7 7 7 7 7 7 7 7 7
6 6 6 6 6 6 6 6 6 6
5 5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3 3 3 3
2 2 2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0
  2 个评论
Dyuman Joshi
Dyuman Joshi 2022-10-10
What have you tried yet? What is the error you are facing? Show your code.
Abdullah Afar
Abdullah Afar 2022-10-11
for i=1:10 for i=1:10 a(i,j)=i-1 end end In this code print 000000000 111111111 222222222 333333333 444444444 555555555 666666666 ... 9999 But I want to 999999999 888888888 777777777 666666666 ... 00000

请先登录,再进行评论。

回答(2 个)

Dyuman Joshi
Dyuman Joshi 2022-10-11
%Updating your solution
%pre-allocation
a=zeros(10);
for i=1:10
for j=1:10
a(i,j)=10-i;
end
end
a
a1 = 10×10
9 9 9 9 9 9 9 9 9 9 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
You can also get the same result (directly) by using some other functions (if using for loop is not necessary) -
[~,y]=meshgrid(9:-1:0)
y = 10×10
9 9 9 9 9 9 9 9 9 9 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
x=repelem((9:-1:0)',1,10)
ans = 10×10
9 9 9 9 9 9 9 9 9 9 8 8 8 8 8 8 8 8 8 8 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 5 5 5 5 5 5 5 5 5 5 4 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0

Abdullah Afar
Abdullah Afar 2022-10-11
for i=1:10 for i=1:10 a(i,j)=i-1 end end
In this code print 000000000 111111111 222222222 333333333 444444444 555555555 666666666 ... 9999
But I want to 999999999 888888888 777777777 666666666 ... 00000

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by