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

조회 수: 20(최근 30일)
Kevin Junior 2013년 9월 17일
댓글: Rik 2022년 10월 17일
for 1:5
fprintf('*') % am stuck right there

댓글을 달려면 로그인하십시오.

### 답변(3개)

Daniel Shub 2013년 9월 17일
편집: 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{:})
##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
Rik 2022년 10월 17일
@Usama Tanveer The answer to this question can be found in the documentation of the plot function, which is probably the first place you should have looked. Did you?

댓글을 달려면 로그인하십시오.

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"?
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Walter Roberson 2013년 9월 17일
Filled or outline only?
Some of the shapes will not require nested for loops.

댓글을 달려면 로그인하십시오.

Kambiz Hosseinpanahi 2018년 6월 26일
편집: Walter Roberson 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);

댓글을 달려면 로그인하십시오.

### 범주

Find more on Loops and Conditional Statements in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by