How do I take spaces out of a string array with multiple rows?
显示 更早的评论
I've searched and found various solutions to this problem that work when you have a variable that has only 1 row. For example:
BCD_space_1row ='1 0 0 1'
%BCD_space_1row has extra spaces that needs to be deleted
BCD_space_1row(isspace(BCD_space_1row)) = []
%this takes out the extra spaces in BCD_space_1row
The result when I run this is:
BCD_space_1row =
1 0 0 1
BCD_space_1row =
1001
which is exactly what I want. This works fine for an array with 1 row but crashes when there are multiple rows. For example:
BCD_space_multirows(1,:) = '1 0 0 1'
BCD_space_multirows(2,:) = '0 1 1 0'
BCD_space_multirows(isspace(BCD_space_multirows)) = []
I want the result after taking out the spaces to be this:
BCD_space_multirows(1,:) = '1001'
BCD_space_multirows(2,:) = '0110'
but my result from above is
BCD_space_multirows =
10010110
I don't understand why the isspace command is giving me this result.
Attempting to run isspace function on 1 row at a time doesn't work either as both examples below also fail
for x = 1,2
BCD_space_multirows(x,:)(isspace(BCD_space_multirows(x,:))) = []
end
BCD_space_multirows(1,:)(isspace(BCD_space_multirows(1,:))) = []
Thanks for any help. Sorry I had to double space everything but when I didn't the preview show no line feeds and I couldn't figure out how to get only a single linefeed. Also the preview seems to have changed from my fixed pitch font (that's better for showing blank spaces) into a proportional font but I think people get the idea - I want all spaces within the string deleted but I need to retain multiple rows and not have all my text concatenated into 1 row.
采纳的回答
更多回答(1 个)
Walter Roberson
2012-11-28
If you are deleting a varying number of blanks from each row of a character array, then the only way to keep it as a string array is to blank pad at the end of lines so that each line remains the same length.
You may wish to consider switching to cell arrays instead, as those can have strings of different lengths.
If you are deleting the same number of blanks from each row of a character array, then after you get the result that is "jammed together", reshape() it to have the number of rows you expect
nrows = size(BCD_space_multirow,1);
BCD_space_multirows(isspace(BCD_space_multirows)) = [];
BCD_space_multirow = reshape(BCD_space_multirow, nrows, []);
2 个评论
Tom Chou
2012-11-28
Walter Roberson
2012-11-29
Oh... just realized that the above reshape() will not work if the blanks are not nicely lined up.
Anyhow, what step is it that you are needing to add spaces for, or that is resulting in unwanted spaces?
BCD = ['0000'; '0001'; '0010'; '0011'; '0100'; '0101'; '0111'; '1000'; '1001'];
BCD_encoded = BCD(sprintf('%d', TheNumber) - '0' + 1, :);
类别
在 帮助中心 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!