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

2 visualizaciones (últimos 30 días)
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

Respuestas (2)

Brendan Hamm
Brendan Hamm el 2 de Mzo. de 2015
Editada: Brendan Hamm el 2 de Mzo. de 2015
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 comentarios
matlabuser12
matlabuser12 el 2 de Mzo. de 2015
would that look like if names(:,n)=strcmp('headers1') or somethign else?
Stephen23
Stephen23 el 2 de Mzo. de 2015
Editada: Stephen23 el 2 de Mzo. de 2015
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.

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 2 de Mzo. de 2015
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.

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by