MATLAB--Basics - Cell Arrays

例1.

Problem 41. Cell joiner

You are given a cell array of strings and a string delimiter. You need to produce one string which is composed of each string from the cell array separated by the delimiter.

For example, this input

 in_cell = {'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur'};
 delim = ' ';

should produce this output:

 out_str = 'Lorem ipsum dolor sit amet consectetur';

(你有一个包含字符串的单元格数组和一个字符串分隔符。你需要生成一个字符串,其中包含单元格数组中的每个字符串,用分隔符隔开。

例如,给定以下输入:

in_cell = {'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur'}; delim = ' ';

应该产生以下输出:

out_str = 'Lorem ipsum dolor sit amet consectetur';)

以下是用MATLAB编写的代码,用于生成包含单元格数组中的每个字符串,并用指定分隔符隔开的字符串: 

% 输入单元格数组和分隔符
in_cell = {'Lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur'};
delim = ' ';

% 生成输出字符串
out_str = strjoin(in_cell, delim);

% 显示结果
disp(['输出字符串: ', out_str]);

这段代码使用了MATLAB内置函数strjoin,将单元格数组中的每个字符串用指定的分隔符连接起来,生成一个字符串。

例2.

 Problem 152. Create a cell array out of a struct

Create a cell array out of a (single) struct with the fieldname in the first column and the value in the second column:

in:

S.foo = 'hello';
S.bar = 3.14;

out:

 {'foo', 'hello';
  'bar', 3.14}

(将一个(单个)结构体转换为一个单元数组,其中第一列是字段名,第二列是对应的值:

输入:

S.foo = 'hello'; S.bar = 3.14;

输出:

{'foo', 'hello'; 'bar', 3.14})
function cellArray = structToCellArray(S)
    fields = fieldnames(S);
    values = struct2cell(S);
    cellArray = [fields, values];
end

你可以调用这个函数并传入一个结构体,它将返回一个单元数组,其中第一列是字段名,第二列是对应的值。例如,如果你有一个结构体 S,其中包含 S.foo = 'hello';S.bar = 3.14;,那么调用 structToCellArray(S) 将返回期望的结果。

例3.

Problem 380. Convert a numerical matrix into a cell array of strings

Given a numerical matrix, output a cell array of string.

For example:

if input = 1:3

output is {'1','2','3'}

which is a cell 1x3

(将一个数字矩阵作为输入,输出一个字符串的单元数组。

例如:

如果输入是 1:3

输出是 {'1','2','3'}

这是一个大小为 1x3 的单元数组。)

function output = m
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值