在 xticklabels 中的值前添加 space (MATLAB)

Add space before values in xticklabels (MATLAB)

我是 MATLAB 的新手,与其他编程语言相比,他们的数据类型/约定确实很吃力。

例如,我创建了一个简单的绘图(例如使用 peaks 命令),并且只想在所有 xticklabels 之前包含一个填充 space。因此,我的 MATLAB/pseudocode 解决方案是:

labels = xticklabels;    # Get labels
newlabels = xticklabels;  # Create new array 
i = 1
for label in labels   # Loop through all labels
    label = ' ' + label   # Add single character pad
    newlabels(i) = label  # Update new labels array
    i = i + 1

set(gca,'XTickLabel', {newlabels})  # Set plot to use new array

请问我怎样才能做到这一点?我觉得这应该很简单

谢谢!

PS,我在MATLAB2017中找到了pad命令,但不是所有的xticklabels都是等长的,因此,我只想添加一个尾随space,而不是固定总字符串长度使用 pad

给定一个字符串元胞数组,最简单的方法是使用 strcat:

labels = {'1','2','3','4'};
newlabels = strcat('x',labels);   % append 'x' because it's more visible

结果:

newlabels =
{
  [1,1] = x1
  [1,2] = x2
  [1,3] = x3
  [1,4] = x4
}

或者,您可以遍历元胞数组并连接到每个字符数组:

newlabels = cell(size(labels));   % preallocate cell array
for k = 1:numel(labels)
   newlabels{k} = ['x', labels{k}];   % concatenate new char to existing label
end