我在上找到了这个通用替代方案MathWorks 文件交换它甚至可以处理 MATLAB 中默认 8 以外的颜色字符串:
如果您只关心默认 8 种颜色字符串的转换,这里有一个我自己编写的函数,用于在 RGB 三元组和短颜色名称(即单个字符)之间来回转换:
function outColor = convert_color(inColor)
charValues = 'rgbcmywk'.'; %#'
rgbValues = [eye(3); 1-eye(3); 1 1 1; 0 0 0];
assert(~isempty(inColor),'convert_color:badInputSize',...
'Input argument must not be empty.');
if ischar(inColor) %# Input is a character string
[isColor,colorIndex] = ismember(inColor(:),charValues);
assert(all(isColor),'convert_color:badInputContents',...
'String input can only contain the characters ''rgbcmywk''.');
outColor = rgbValues(colorIndex,:);
elseif isnumeric(inColor) || islogical(inColor) %# Input is a numeric or
%# logical array
assert(size(inColor,2) == 3,'convert_color:badInputSize',...
'Numeric input must be an N-by-3 matrix');
inColor = double(inColor); %# Convert input to type double
scaleIndex = max(inColor,[],2) > 1; %# Find rows with values > 1
inColor(scaleIndex,:) = inColor(scaleIndex,:)./255; %# Scale by 255
[isColor,colorIndex] = ismember(inColor,rgbValues,'rows');
assert(all(isColor),'convert_color:badInputContents',...
'RGB input must define one of the colors ''rgbcmywk''.');
outColor = charValues(colorIndex(:));
else %# Input is an invalid type
error('convert_color:badInputType',...
'Input must be a character or numeric array.');
end
请注意,此函数允许您输入字符串or一个 N×3 数值或逻辑数组(RGB 值从 0 到 1 或 0 到 255),它返回相反的颜色表示。它还使用了该功能ISMEMBER进行转换。