How to maniplulate data in one array if conditions are met in another array?

3 次查看(过去 30 天)
I have an array of numeric data, and I have another with the string headers of that data. these two arrays match in terms of what header goes with which column. I want to write an if statement that says for each column in the headers array, if the string value in column 1 for example equals 'cheeto', then take column 1 from the data array and multiply all values by 10 (or apply some function). if it equals a different string do something else, and then move on to the next string in the header array and repeat the process.
Somewhere down the line I would like to have a repository of formulas that can be applied for each string case but i will work on that later.
Here is what I have so far. names is the array with 1 column and some string headers and Data is the new data file, while dataToRead is the original data array. there must be a betetr way to do this, I might have anwyhere from 1 to 20 formulas/headers so make a million if else statements seems wrong.
for n=1:length(names)
if names{:,n}=='header1'
Data(:,n)=3*DataToRead(:,n+1); %I have a time stamp in column 1 i dont want to act upon
else
if names{:,n}=='header2'
Data(:,n)=4*DataToRead(:,n+1)
else
if names{:,n}=='header4'
Data(:,n)=0*DataToRead(:,n+1)
end
end
end
end

回答(2 个)

Brendan Hamm
Brendan Hamm 2015-3-2
编辑:Brendan Hamm 2015-3-2
You do not want to use "==" on textual data. Look at strcmp() or strcmpi(). Also, in MATLAB you can say
if condition
do something
elseif condition2
do something else
end
There is no need for all of the ends
  2 个评论
Stephen23
Stephen23 2015-3-2
编辑:Stephen23 2015-3-2
doc strcmp
While learning things by trial-and-error is great fun sometimes, you should consider reading the documentation. The lovely people at The MathWorks didn't put it there to look nice or to fill in a few GB of harddrive space.

请先登录,再进行评论。


Image Analyst
Image Analyst 2015-3-2
Don't use names{:,n}=='header2' use the ismember() function instead. Take a look at the help and see if you can figure it out. Come back here is there's no way you can figure it out.

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by