How to remove quotation marks from each element of my array

16 ビュー (過去 30 日間)
Will Pihir
Will Pihir 2021 年 9 月 1 日
コメント済み: Will Pihir 2021 年 9 月 1 日
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 Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by