Filter löschen
Filter löschen

How to remove quotation marks from each element of my array

11 Ansichten (letzte 30 Tage)
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 Kommentare
Stephen23
Stephen23 am 1 Sep. 2021
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 am 1 Sep. 2021
I've been instructed by my teacher to use a nested loop.
Thanks for the help

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Chunru
Chunru am 1 Sep. 2021
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 - - - - - - - - -

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by