How do I store data that meet conditions of an if statement

44 visualizaciones (últimos 30 días)
NA
NA el 1 de Feb. de 2021
Comentada: NA el 3 de Feb. de 2021
Hi All,
I'm slightly struggling trying to get my code to work, and I hope someone can point me in the right direction.
Very briedly, I have two vectors, 'xx' and 'yy'. I created a matrix using these two vectors, 'xy'. If xy(:,1) is ==1, I would like to store the corresponding cell in xy(:,2) in a seperate variable, 'data'. Otherwise, if the logical expression = 0, I'd like that cell to be a NaN
xx=[-3; -3; -3; -3; -3; -3; 1; -2; -2; -3; -3; -2; 1; 1; 1; -2; 1; 1; ];
yy=[26.28; 36.96; 90.00; 90.00; 90.00; 90.00; 27.85; 29.97; 47.03; 90.00; 67.22; 78.87; 19.60; 9.00; 2.00; 3.41; 1.88; 2.50];
xy=[xx yy];
for i=1:size(xy(:,1),1)
if xy(:,1)==1
data=xy(:,2);
else
data=NaN;
end
end
Thanks in advance.
Cheers

Respuesta aceptada

Jan
Jan el 1 de Feb. de 2021
Editada: Jan el 1 de Feb. de 2021
xx = [-3; -3; -3; -3; -3; -3; 1; -2; -2; -3; -3; -2; 1; 1; 1; -2; 1; 1; ];
yy = [26.28; 36.96; 90.00; 90.00; 90.00; 90.00; 27.85; 29.97; ...
47.03; 90.00; 67.22; 78.87; 19.60; 9.00; 2.00; 3.41; 1.88; 2.50];
xy = [xx yy];
data = nan(size(xx));
match = (xx == 1);
data(match) = xy(match, 2);
This "vectorized" method is faster and nicer than a loop. But with a loop:
data = nan(size(xy, 1), 1);
for i = 1:size(xy, 1) % better than: size(xy(:,1),1)
if xy(i, 1) == 1
data = xy(i, 2);
end
end
  5 comentarios
dpb
dpb el 2 de Feb. de 2021
I posted a demonstration of what happens with dynamic allocation just a day or so ago at<Comment_1298378>
NA
NA el 3 de Feb. de 2021
Thanks dpb, thats very useful information. Cheers

Iniciar sesión para comentar.

Más respuestas (2)

dpb
dpb el 1 de Feb. de 2021
Don't need any loops nor the explicity xy array that is duplicate of existing data.
data=nan(size(x,1),2); % initialize to NaN
ix=(xx==1); % logical addressing vector of wanted locations
data(ix,:)=[xx(ix) yy(ix)]; % set data values
Alternatively,
data=[xx yy]; % initialize to data
data(data(:,1),:)=nan; % set unwanted values to NaN
  1 comentario
NA
NA el 1 de Feb. de 2021
I wrote it usuing a for loop because it's a subset of a larger code (and needs to be incorporated within a loop). But thank you for your feedback :) Cheers

Iniciar sesión para comentar.


J Chen
J Chen el 1 de Feb. de 2021
You over wrote the variable data. One soluation is to change data to data(i).
  1 comentario
dpb
dpb el 1 de Feb. de 2021
The if condition will never be satisfied. if expression is true IFF all elements of expression are true.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by