我正在尝试创建一个字符串数组,它将以这种方式从文本文件中读取字符串值:
labels = textread(file_name, '%s');
基本上,对于文本文件file_name的每一行中的每个字符串,我想将此字符串放在最终字符串数组的10个位置,稍后将保存在另一个文本文件中。
我在代码中所做的是,对于file_name中的每个字符串,我将此字符串放在临时单元数组的10个位置,然后以这种方式将此数组与最终数组连接:
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector{1:10}=labels{i};
final_vector=horzcat(final_vector,temp_vector);
end
但是当我运行代码时,会出现以下错误:
The right hand side of this assignment has too few values to satisfy the left hand side.
Error in my_example_code (line 16)
temp_vector{1:10}=labels{i};
我在matlab的单元格中太新手了,我真的不知道发生了什么。你知道发生了什么,甚至更好地解决了我的问题吗?
答案 0 :(得分:1)
使用deal
并将左侧放在方括号中:
labels{1} = 'Hello World!'
temp_vector = cell(10,1)
[temp_vector{1:10}] = deal(labels{1});
这是有效的,因为deal
可以将一个值分配给多个输出[a,b,c,...]
。仅temp_vector{1:10}
创建comma-separated list并将其放入[]
创建输出数组[temp_vector{1}, temp_vector{2}, ...]
,然后可以deal
填充。
这种情况正在发生,因为您希望将一个值分发到 10个单元格 - 但Matlab希望您希望将 10个值分配给 10个细胞。所以另一种方法,可能更多的逻辑,但更慢,将是:
n = 10;
temp_vector(1:n) = repmat(labels(1),n,1);
答案 1 :(得分:0)
我还找到了另一个解决方案
final_vector='';
for i=1:size(labels)
temp_vector=cell(1,10);
temp_vector(:,1:10)=cellstr(labels{i});
final_vector=horzcat(final_vector,temp_vector);
end