在 MatLab 中,如何从元胞数组创建字符向量?

In MatLab, how can I create a character vector from a cell array?

我显然无法区分不同类型的向量和数组以及字符串、cellstr、char 等命令。我的代码在另一个网络上,但基本上,我在 imread 语句中说出参数时出错必须是字符向量。参数是一个 1x30 的文件名数组,并且是一个元胞数组,因为我使用了 iscell 命令,它返回了 1。我已经尝试了上面列出的命令的几种组合,并且一直在尽我所能阅读但无法确定如何更改将 1x30 元胞数组转换为字符向量,以便 imread 语句起作用。文件名从文件夹(使用 uigetfile)中读取为 757-01.bmp、757-02.bmp ... 757-30.bmp。我假设我需要将它们设为 '757-01.bmp'、'757-02.bmp' ... '757-30.bmp' 并可能变成 30x1 向量 vice 1x30?或者对于代码接下来会遇到的 for 循环来说,这可能无关紧要……?感谢您的帮助...

[imagefiles,file_path]=uigetfile({'*.jpeg;*.jpg;*.bmp;*.tif;*.tiff;*.png;*.gif','Image Files (JPEG, BMP, TIFF, PNG and GIF)'},'Select Images','multiselect','on');
imagefiles = cellstr(imagefiles);
imagefiles = sort(imagefiles);
nfiles = length(imagefiles);

r = inputdlg('At what pixel row do you want to start the cropping?        .','Row');
r = str2num(r{l});

c = inputdlg('At what pixel column do you want to start the cropping (Must be > 0)?        .','Column');
c = str2num(c{l});

h = inputdlg('How many pixel rows do you want to include in the crop?        .','Height');
h = str2num(h{l});

w = inputdlg('How many pixel columns do you want to include in the crop?        .','Width');
w = str2num(w{l});

factor = inputdlg('By what real number factor do you want to enlarge the cropped image?        .','Factor');
factor = str2num(factor{l});

outdimR = h * factor;
outdimC = w * factor;

for loop=l:nfiles
    filename = imagefiles(loop);
    [mybmp, map] = imread(filename);
    myimage = ind2rgb(mybmp,map);
    crop = myimage(r:r+h-1, c:c+w-1, :);
    imwrite(crop, sprintf('crop757-%03i.bmp',loop));
end

关于您原来的问题:

In MatLab, how can I create a character vector from a cell array?

您可以使用单元格访问器操作数 ({}) 从您的单元格中获取字符串,正如@ben-voight 指出的那样,或者将 char() 包裹在您的语句周围(我会接受 Ben 的建议).

关于您的后续问题:

It errors out at imread saying File "757-01.bmp" does not exist. In the imagefiles array, the first of 30 values is 757-01.bmp (no quotes) but I don't know if MatLab putting quotes around the file name means its looking for a value with quotes in the array or not.

听起来您的文件位于另一个目录中,而不是您 运行 您的代码所在的目录。

使用 fullfile 创建完整文件名以使用文件的绝对路径而不是相对路径(此处不起作用)。

假设您的文件位于路径 ~/bpfreefly/images/.

然后你可以这样修改你的代码:

imgPath = '~/bpfreefly/images/'
for loop=l:nfiles
    filename = fullfile(imgPath,imagefiles{loop});
    [mybmp, map] = imread(filename);
    myimage = ind2rgb(mybmp,map);
    crop = myimage(r:r+h-1, c:c+w-1, :);
    imwrite(crop, sprintf('crop757-%03i.bmp',loop));
 end

顺便说一下,您可以从 uigetfile 的第二个输出参数中获取路径名。