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 = matrixToStringArray(matrix)
    [m, n] = size(matrix);
    output = cell(1, m * n);
    k = 1;
    for i = 1:m
        for j = 1:n
            output{k} = num2str(matrix(i, j));
            k = k + 1;
        end
    end
end

你可以调用这个函数并传入你的数字矩阵作为参数,它会返回相应的字符串单元数组。

例4.

Problem 967. Split a string into chunks of specified length

Given a string and a vector of integers, break the string into chunks whose lengths are given by the elements of the vector. Extra characters leftover at the end should be dropped. Example:

break_string('I seem to be having tremendous difficulty with my lifestyle',[4 1 5 22])

should return a 4x1 cell array:

ans = 
  'I se'    'e'    'm to '    'be having tremendous d'

给定一个字符串和一个整数向量,将字符串分割成由向量元素指定长度的块。末尾多余的字符应该被丢弃。例如:

break_string('I seem to be having tremendous difficulty with my lifestyle',[4 1 5 22])

应该返回一个 4x1 的单元数组:

ans = 'I se' 'e' 'm to ' 'be having tremendous d')
function chunks = break_string(str, lengths)
    chunks = cell(length(lengths), 1);
    start_idx = 1;
    for i = 1:length(lengths)
        end_idx = start_idx + lengths(i) - 1;
        if end_idx > length(str)
            chunks{i} = str(start_idx:end);
            break;
        else
            chunks{i} = str(start_idx:end_idx);
            start_idx = end_idx + 1;
        end
    end
end

 你可以将这个函数保存在一个名为 break_string.m 的文件中。然后,你可以像这样调用它:

result = break_string('I seem to be having tremendous difficulty with my lifestyle', [4 1 5 22]);
disp(result);

这将输出所需的结果:

I se    e    m to     be having tremendous d

例5.

Problem 1899. Convert a Cell Array into an Array

Given a square cell array:

 x = {'01', '56'; '234', '789'};

return a single character array:

 y = '0123456789'

(给定一个方形的单元格数组:

x = {'01', '56'; '234', '789'};

返回一个单一的字符数组:

y = '0123456789'

可以使用循环将单元格数组中的每个单元格连接起来,然后使用字符串函数 join 来连接所有的字符串。以下是MATLAB代码示例:

x = {'01', '56'; '234', '789'};
y = join(x(:)', ''); % 将单元格数组展开为一维数组,然后连接所有字符串
disp(y);

 这将输出:

0123456789

这样,变量 y 就是连接后的字符数组。

例6.

Problem 1971. Remove element(s) from cell array

You can easily remove an element (or a column in any dimension) from a normal matrix, but assigning that value (or range) empty. For example

A = 1:10
A(5) = []

results in

1 2 3 4 6 7 8 9 10

You task is to find the shortest, elegant, way in Matlab to do the same for cell arrays. Regexp, eval, and other workarounds that trick mtree are considered stupid, and will not be appreciated.

可以使用花括号索引和花括号删除来从单元格数组中删除元素。以下是一个示例:

A = {'a', 'b', 'c', 'd', 'e'};
A(3) = []; % 删除第三个元素
disp(A);

 这将输出:

'a'    'b'    'd'    'e'

这样,你就从单元格数组 A 中移除了第三个元素。

例7.

Problem 1036. Cell Counting: How Many Draws?

You are given a cell array containing information about a number of soccer games. Each cell contains one of the following:

  • 'H', meaning the home team won
  • 'A', meaning the away team won
  • 'D', meaning a draw, or tie game

So if

 games = {'D','D','A','H','D','H'}

then

 draws = 3

(你被给予一个包含关于多场足球比赛信息的单元数组。每个单元格包含以下之一:

  • 'H',表示主队获胜
  • 'A',表示客队获胜
  • 'D',表示平局比赛

因此,如果

games = {'D','D','A','H','D','H'}

那么

draws = 3)

下面是一个MATLAB程序,用于计算平局比赛的数量:

function draws = countDraws(games)
    draws = sum(strcmp(games, 'D'));
end

 你可以将这个函数用于给定的游戏单元数组,它将返回平局比赛的数量。例如,对于给定的 games 数组,可以这样使用:

games = {'D','D','A','H','D','H'};
draws = countDraws(games);
disp(['平局比赛的数量为:', num2str(draws)]);

例8.

Problem 43677. String Array Basics, Part 1: Convert Cell Array to String Array; No Missing Values

String array and cell array are two types of containers for storing pieces of data. In this problem, you will be given a cell array of character vectors. Your job is to convert the cell array to a string array, which stores the same pieces of text data.

To begin with, let's assume that there are no missing type values in the input cell array.

Example:

Input:

>> x = {'I','Love','MATLAB'}
x =
  1×3 cell array
    'I'    'Love'    'MATLAB'
Output:

>> y = strings(size(x));
>> [y{:}] = x{:}
y = 
  1×3 string array
    "I"    "Love"    "MATLAB"

Note that the example shown above is not the best way to solve this problem. Try other approaches in order to achieve a leading score.

Related Problems in this series:

(字符串数组和单元格数组是存储数据片段的两种类型的容器。在这个问题中,你将会获得一个包含字符向量的单元格数组。你的任务是将单元格数组转换为字符串数组,以存储相同的文本数据。

首先,让我们假设输入单元格数组中没有缺失的类型值。

示例:

输入:

>> x = {'I','Love','MATLAB'} x = 1×3 cell array 'I' 'Love' 'MATLAB'

输出:

>> y = strings(size(x)); >> [y{:}] = x{:} y = 1×3 string array "I" "Love" "MATLAB"

注意,上面显示的示例并不是解决这个问题的最佳方法。尝试其他方法以获得领先的分数。)

 以下是将单元格数组转换为字符串数组的MATLAB程序:

% 给定的单元格数组
x = {'I','Love','MATLAB'};

% 创建与单元格数组大小相同的字符串数组
y = strings(size(x));

% 将单元格数组的内容赋值给字符串数组
[y{:}] = x{:};

% 显示结果
disp(y);

这段代码创建了一个与输入单元格数组大小相同的字符串数组,然后将单元格数组的内容赋值给字符串数组。最后,它显示了转换后的字符串数组。

例9

Problem 1755. Fix the last element of a cell array

Note: this is lifted directly from Puzzler for a Monday (on MATLAB Answers) by the cyclist.

----

Given a cell array of strings

 A = {'MATLAB','HURRAY','SPARKLY','KITTENS','FUN'};

and a particular string value

 B = 'KITTENS';

ensure that B is the last element of the cell array. If it isn't, move it to the end of A.

You cannot assume that B appears at all (in which case return A unchanged), but you can assume B does not appear more than once.

So in the example,

 C = {'MATLAB','HURRAY','SPARKLY','FUN','KITTENS'};

(注意:这直接引用了来自MATLAB Answers上的“周一的智力题”中的自行车手的内容。


给定一个字符串的单元格数组

A = {'MATLAB','HURRAY','SPARKLY','KITTENS','FUN'};

以及一个特定的字符串值

B = 'KITTENS';

确保B是单元格数组的最后一个元素。如果不是,将其移动到A的末尾。

你不能假设B会出现(如果没有出现,则返回未更改的A),但你可以假设B不会出现超过一次。

因此在这个示例中,

C = {'MATLAB','HURRAY','SPARKLY','FUN','KITTENS'};

 可以使用MATLAB的字符串和单元格数组操作来实现这个任务。以下是一个示例代码:

strcmp是用于做字符串比较的函数,按复杂程度及比较对像的不同主要可以分为以下三种情况:

这段代码首先检查字符串B是否在单元格数组A中,如果在,则将其移动到A的末尾;如果不在,则保持A不变。运行这段代码会得到输出:

'MATLAB'    'HURRAY'    'SPARKLY'    'FUN'    'KITTENS'

这样,你就确保了B是单元格数组的最后一个元素。


strcmp是用于做字符串比较的函数,按复杂程度及比较对像的不同主要可以分为以下三种情况:

1. TF=strcmp(s1,s2);

2. TF=strcmp(s,c);

3. TF=strcmp(c1,c2);   

matlab中strcmp函数的使用_matlab matcmp-CSDN博客

例10

Problem 2300. Natural numbers in string form

Create a cell array of strings containing the first n natural numbers. Slightly harder than it seems like it should be.

Example

 >> y = naturalnumbers(4)
 y =
   '1'   '2'   '3'   '4'

下面是一个 MATLAB 程序,用于创建包含前 n 个自然数的字符串单元数组:

function numbers = naturalnumbers(n)
    numbers = cell(1, n);
    for i = 1:n
        numbers{i} = num2str(i);
    end
end

 你可以调用这个函数并传入你想要的自然数数量作为参数,它会返回相应的字符串单元数组。例如:

n = 4;
numbers = naturalnumbers(n);
disp(numbers);

这将输出:

'1'   '2'   '3'   '4'

num2str函数功能: 
把数值转换成字符串, 转换后可以使用fprintf或disp函数进行输出。在matlab命令窗口中键入doc num2str或help num2str即可获得该函数的帮助信息。
  
语法格式:
  str = num2str(A)
  把数组A中的数转换成字符串表示形式。
  str = num2str(A, precision)
  把数组A转换成字符串形式表示,precision表示精度, 比如precision为3表示保留最多3位有效数字, 例如0.5345转换后为0.534,1.2345转换后为1.23。即从左边第一个不为0的数开始保留3个数值。
  str = num2str(A, format)
  按format指定格式进行格式化转换,通常'%11.4g'是默认的。
————————————————
原文链接:https://blog.csdn.net/smf0504/article/details/51836062

  • 15
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值