如何使用matlab创建一个asterik矩形

时间:2016-02-18 17:00:23

标签: matlab

我是matlab的初学者。任何人都可以告诉如何在图像中创建一个asterik矩形:

enter image description here

3 个答案:

答案 0 :(得分:6)

这是一种没有循环的方法:

m = 5;     %// number of rows
n = 12;    %// number of cols
c = ' ';   %// inner character
C = '*';   %// outer character
x = repmat(c, m, n);   %// create m x n array of c
x([1 end], :) = C;     %// replace top and bottom with C
x(:, [1 end]) = C;     %// replace left and right with C

这给出了

>> disp(x)
************
*          *
*          *
*          *
************

答案 1 :(得分:2)

%symbol to print
symbol = '*';

%How many Rows in your rectangle
numRows = 20;
%How many columns in your rectangle
numColumns = 10;

%loop through each row
for currentRow = 1 : numRows
    %loop thourgh each column
    for currentColumn = 1 : numColumns
        %if we are in the first or last row print a symbol
        if(currentRow == 1 || currentRow == numRows)
            fprintf('%s',symbol)
        %if we are in the first or last column print a symbol
        elseif(currentColumn == 1 || currentColumn == numColumns)
            fprintf('%s',symbol)
        %otherwise print a blank space (file the middle)
        else
            fprintf(' ')
        end
    end
    %at the end of the column move to the next line
    fprintf('\n');
end

答案 2 :(得分:2)

我必须说,我发布这个答案的唯一原因(Rob F。的答案会很好)是因为它让我有机会使用我不喜欢的MATLAB函数&# 39;经常使用:blanks

我们走了:

row_count = 5;   %// number of rows we want
col_count = 17;  %// number of columns
A = '';          %// our starting (blank) char array
                 %// note that growing arrays like this is sloooow
                 %// but for our purposes, it should be fine

for row = 1:row_count
   A(row,:) = blanks(col_count);   %// make each row a row of blanks
end

%// now add the asterisks using row and column indices
A(1,:) = '*';           %// top row
A(row_count,:) = '*';   %// or `A(end,:)` - bottom row
A(:,1) = '*';           %// left column
A(:,col_count) = '*';   %// or `A(:,end)` - right column

disp(A);

结果:

*****************
*               *
*               *
*               *
*****************