Borrar filtros
Borrar filtros

if function in cell arrays

2 visualizaciones (últimos 30 días)
gsourop
gsourop el 19 de Nov. de 2016
Comentada: the cyclist el 19 de Nov. de 2016
Hi everyone,
I try to use to use the if function in cell arrays. If I have A that is 2x100 cells and each cell contains a 6x1 vector. I need to set the following constraint:
for k=1:2
for t=1:100
if A{k,t}(:,1)<-1;
A{k,t}(:,1)=-1;
elseif A{k,t}(:,1)>2;
a{k,t}(:,1)=2;
end;
end;
end;
This code does not deliver an error. However, it doesn't do what I aim at. It should go on each cell and check the each value of the vectors have a value over or lower than the if statements.
Thanks in advance

Respuestas (1)

the cyclist
the cyclist el 19 de Nov. de 2016
Editada: the cyclist el 19 de Nov. de 2016
There are a couple issues with your code. The main issue is that the line
A{k,t}(:,1)<-1
will have a vector output, and therefore the if statement is not doing what you expect. (It would have to be true for every value in the vector, to trigger the if.)
A more straightforward way to do this is as follows:
for k=1:2
for t=1:100
A{k,t} = max(A{k,t},-1);
A{k,t} = min(A{k,t}, 2);
end
end
which compares each element of the vector to the threshold value, and replaces it if necessary.
This same operation can be done very compactly, eliminating the for loops completely, with the cellfun function instead:
A = cellfun(@(x)max(x,-1),A,'UniformOutput',false);
A = cellfun(@(x)min(x, 2),A,'UniformOutput',false);
You can even collapse this into a one-liner:
A = cellfun(@(x)min(2,max(x,-1)),A,'UniformOutput',false);
but what you are doing starts to get a little "obfuscated".
(The for loop seems to be the faster method, though, in the limited testing I did.)
  2 comentarios
gsourop
gsourop el 19 de Nov. de 2016
Thanks a lot! I've started working on cell arrays to create a more compact and fast way for the first steps of my code, but then it has started getting more comfusing than I expected.
the cyclist
the cyclist el 19 de Nov. de 2016
The best form of thanks is upvoting and/or accepting helpful answers, which rewards the contributors, and guides future users.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by