2017-11-03 252 views
0

我是MATLAB新手,与其他编程语言相比,他们的数据类型/约定真的很挣扎。例如,我创建了一个简单的绘图(例如使用峰值命令),并且只想在所有xticklabels之前包含填充空格。我的MATLAB /伪代码解决方案是这样的:在xticklabels中的值之前添加空格(MATLAB)

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垫命令,但不是所有的xticklabels的长度相等,因此,我只想增加一个尾部的空格,用垫

回答

2

最简单的方法不能解决总字符串长度,给出一个字符串单元阵列,是使用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 
相关问题