Does someone know how to print a square onto the command window using for loops????

70 ビュー (過去 30 日間)
Kevin Junior 2013 年 9 月 17 日

for 1:5
fprintf('*') % am stuck right there

0 件のコメント

サインイン to comment.

回答 (3 件)

Daniel Shub 2013 年 9 月 17 日

I am not sure why you want to use a loop or fprintf. The simplest, but potentially not square enough solution for a filled square
N = 5;
x = repmat(char(42), N, N);
disp(x);
*****
*****
*****
*****
*****
For an unfilled square you can do
N = 5;
x = repmat(char(42), N, N);
x(2:end-1, 2:end-1) = char(32);
disp(x);
*****
* *
* *
* *
*****
On my system I get a squarer square with
x = repmat([char(42), char(32)], N, N)
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Depending on how perfect you want, maybe you could use a thin space or a wide space.
For a filled diamond
a = [fliplr(tril(true(N))), tril(true(N)); triu(true(N)), fliplr(triu(true(N)))];
x = repmat(char(32), 2*N, 2*N);
x(a) = char(42);
disp(x)
**
****
******
********
**********
**********
********
******
****
**
For an empty diamond
a = [fliplr(triu(tril(true(N)))), triu(tril(true(N))); tril(triu(true(N))), fliplr(tril(triu(true(N))))];
x = repmat(char(32), 2*N, 2*N);
x(a) = char(42);
disp(x)
**
* *
* *
* *
* *
* *
* *
* *
* *
**
If you really need to use fprintf
y = mat2cell(x(:), ones(numel(x), 1), 1);
fprintf([repmat('%s', 1, 2*N), '\n'], y{:})

2 件のコメント

Kevin Junior 2013 年 9 月 17 日
I am trying to print a diamond with an empty space in the middle using fprintf statements
Daniel Shub 2013 年 9 月 17 日
See my edit for diamonds.

サインイン to comment.

Simon 2013 年 9 月 17 日
Hi!
You should start reading here: http://www.mathworks.com/help/matlab/control-flow.html This explains how to use loops and their syntax.
What do you mean with "square"?

3 件のコメント

Kevin Junior 2013 年 9 月 17 日
like printing shapes using asterix, for instance a rectangle, a square, a diamond i know I will definitely have to use nested loops
Walter Roberson 2013 年 9 月 17 日
Filled or outline only?
Some of the shapes will not require nested for loops.
Kevin Junior 2013 年 9 月 17 日
unfilled diamond using just fprintf statements

サインイン to comment.

Kambiz Hosseinpanahi 2018 年 6 月 26 日

clc
clear
n=10;
A=repmat(char(42),n,n);
A(1:end-1,2:end)=char(32);
for i=2:10
A(i,i)=char(42);
end
disp(A);

0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。

Translated by