so I'm supposed to write a function that takes an input of a string and an integer and then creates a square using the string to make it up and the integer as the dimensions. Here is an example:
square('.',6)
......
......
......
......
......
......
this is what I have as code:
function [ ] = square( s,num )
square = zeros(num, num);
for i = 1:num
for j=1:num
square(i,j) = s;
end
end
format
square
end
my output when I input ('.',6) is
46 46 46 46 46 46
46 46 46 46 46 46
46 46 46 46 46 46
46 46 46 46 46 46
46 46 46 46 46 46
46 46 46 46 46 46
what am I doing wrong??

 Akzeptierte Antwort

David Goodmanson
David Goodmanson am 13 Nov. 2016
Bearbeitet: David Goodmanson am 13 Nov. 2016

0 Stimmen

Hi retro, the reason for this is that zeros(n,n), is a matrix of double precision numbers. When you try to insert '.', Matlab converts that string to a number. You can see this with
>> abs('.') ans = 46
You have to create a string matrix first. One way to do this is with
m = blanks(9) % row vector of 9 blanks, blank = ' '
Then use the "reshape" command to make a 3x3 matrix out of this and proceed as before.

1 Kommentar

I also want to mention what 'blanks' is up to. For a row vector of length n:
space = ' ';
vector_of_blanks = space(ones(1,n));
This is known as 'Tony's trick' (Tony Booer, Schlumberger) and it has been around for a long time. It generalizes quite well, so to get an (n x m) matrix of periods:
str = '.';
matrix_of_dots = str(ones(n,m));
Matlab has the 'string' and 'strings' command to deal with this stuff but you tend to end up with double quote marks around every displayed matrix element which is not what you want in this case.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by