MATLAB:使用带有字符串的If语句从其他数组返回值
我有一个matlab程序,我从excel中导入了一些数组。我正在尝试编写一个if语句,该语句在第一个数组中查找,例如:MATLAB:使用带有字符串的If语句从其他数组返回值,matlab,Matlab,我有一个matlab程序,我从excel中导入了一些数组。我正在尝试编写一个if语句,该语句在第一个数组中查找,例如: Thing-1 Thing-1 Thing-3 Thing-5 如果一列是“Thing-1”,那么它将转到另一个数组,并计算3个值,这些值将被赋予不同的变量名……任何指导都将不胜感激!谢谢 问题是。。。不太清楚,但让我试着给你一些建议 假设您从Excel工作簿中读取了一些数据,其中第一行是标题,后面是许多带数字的行 [num,txt] = xlsread(ex
Thing-1 Thing-1 Thing-3 Thing-5
如果一列是“Thing-1”,那么它将转到另一个数组,并计算3个值,这些值将被赋予不同的变量名……任何指导都将不胜感激!谢谢 问题是。。。不太清楚,但让我试着给你一些建议 假设您从Excel工作簿中读取了一些数据,其中第一行是标题,后面是许多带数字的行
[num,txt] = xlsread(excelFileName);
因此num
包含数字数据和txt
字符串列标题
然后可以在列标题中检查字符串Thing-1
thingOneIdx
是一个数组,在标题的列中包含索引。在您的示例中,它应该是[12]
,因为前两列是Thing-1
thingOneIdx = find(strcmp('Thing-1',txt));
您可以创建三个单元格数组,firstValue
、secondValue
和thirdValue
,它们将存储三次计算的结果。如果您需要将Thing-1
数据保存在一个额外的数组中,您可以类似地这样做
%# define cell arrays (do it in one go using deal)
[firstValue,secondValue,thirdValue] = deal(cell(length(thingOneIdx),1));
%# for simplicity and readability, loop through isThingOneIdx to assign data
for ct = 1:length(thingOneIdx)
myIdx = thingOneIdx(ct);
firstValue{ct} = someCalculation(num(myIdx,:));
secondValue{ct} = someOtherCalculation(num(myIdx,:));
%# etc
end
您需要一个类似于Excel中的vlookup的函数 我写了一本。以下是源代码:
function [content, index] = vlookup(m, e, column, lookcolumn)
if isempty(m) || isempty(e), return; end
if nargin <= 3, lookcolumn = 1; end
isechar = ischar(e);
assert(isechar || isnumeric(e), 'the second parameter must be a string or numeric');
if iscell(m)
content = {}; index = [];
if isechar
index = find(strcmp(e, m(:, lookcolumn)));
content = m(index, column);
else
for i = 1:size(m, 1)
if isnumeric(m{i, lookcolumn}) && m{i, lookcolumn} == e
content = [content; m(i, column)]; %#ok<*AGROW>
index = [index; i];
end
end
end
else
assert(~isechar, 'When the first para is a matrix, the second para must be numeric');
index = find(m(:, lookcolumn) == e);
content = m(index, column);
end
function[content,index]=vlookup(m,e,column,lookcolumn)
如果isempty(m)| | isempty(e),返回;结束
如果nargin学习如何格式化代码。编辑答案时,请查看文本字段上方的工具栏和右侧的橙色问号。