How to remove quotation marks from each element of my array

11 次查看(过去 30 天)
Hi Guys,
I have made a 10x10 gameboard with the first row and column containing the numbers from 0 to 9.
When I display the gameboard, each element has quotation marks around it which I would like to remove. Note that the gameboard isn't correctly displayed when using ' ' instead of " ".
Any help is much appreciated.
%Initialising array and parameters
gameboard = [];
rows = 10;
cols = 10;
%Populating with nested loop
for r = [1:rows]
gameboardRow = [];
for c = [1:cols]
hypens = "-";
gameboardRow = [gameboardRow hypens];
end
gameboard = [gameboard; gameboardRow];
end
gameboard(1,:) = [0:9];
gameboard(:, 1) = [0:9];
disp(gameboard);
"0" "1" "2" "3" "4" "5" "6" "7" "8" "9"
"1" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"2" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"3" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"4" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"5" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"6" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"7" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"8" "-" "-" "-" "-" "-" "-" "-" "-" "-"
"9" "-" "-" "-" "-" "-" "-" "-" "-" "-"
  3 个评论
Stephen23
Stephen23 2021-9-1
for r = [1:rows]
% ^ ^ superflouus, get rid of them.
Most of your code consists of inefficient nested loops that simply generate a string matrix of the hyphen character: expanding arrays inside loops should be avoided. Rather than using nested loops simply use much simpler REPMAT:
nrows = 5;
ncols = 5;
M = repmat("-",nrows,ncols)
M = 5×5 string array
"-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-"
Assuming that you require the matrix to be string type, then most likely the answer to your question is to write your own display routine using FPRINTF. Doing so will give you much more control over how it looks when displayed.
Will Pihir
Will Pihir 2021-9-1
I've been instructed by my teacher to use a nested loop.
Thanks for the help

请先登录,再进行评论。

采纳的回答

Chunru
Chunru 2021-9-1
gameboard = [];
rows = 10;
cols = 10;
%Populating with nested loop
gameboard = repmat('-', 10, 10);
gameboard(1, :) = ('0':'9');
gameboard(:, 1) = ('0':'9');
disp(gameboard);
0123456789 1--------- 2--------- 3--------- 4--------- 5--------- 6--------- 7--------- 8--------- 9---------
% Place space along rows
gameboard = repmat('- ', 10, 10);
gameboard(1, 1:2:end) = ('0':'9');
gameboard(:, 1) = ('0':'9');
disp(gameboard);
0 1 2 3 4 5 6 7 8 9 1 - - - - - - - - - 2 - - - - - - - - - 3 - - - - - - - - - 4 - - - - - - - - - 5 - - - - - - - - - 6 - - - - - - - - - 7 - - - - - - - - - 8 - - - - - - - - - 9 - - - - - - - - -

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by