Info

この質問は閉じられています。 編集または回答するには再度開いてください。

How to obtain the x and y vectors for those whose state is set to i in MATLAB

1 回表示 (過去 30 日間)
Khadeja Khan
Khadeja Khan 2020 年 5 月 7 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have a MATLAB function called nearInfectious2 which represents six people. It takes in parameters of an array of x coordinates, an array of y coordinates, different states relating to those coordinates "s" for susceptible, "i" for infectious and "r" for recovered and lastly a radius. I want to store an array or array(s) of the x and y coordinates for those people whose state is "i". This is what I have thus far, but it is also including the other coordinates which is not what I want. How can I get it to just return arrays with coordinates relating to those whose state is "i"? This is what I have thus far:
[x,y]=nearInfectious2([3,350,150,20,204,103],[92,9,200,5,350,34],["s","i","s","r","i","i"],20);
function [x,y] = nearInfectious2(x,y,states,radius)
for j=1:6
if states(j) == "i"
x(j)=x(j);
y(j)=y(j);
end
end
disp([x])
disp([y])
end
After I have the array of coordinates relating to the people who's states are "i", I want to calculate the distance (using the normal distance formula sqrt((x2 - x1)^2 + (y2 - y1)^2)) between any individuals whose state is "s", to those whose state is "i" to see if it less than radius apart. Any help is greatly appreciated.
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 5 月 7 日
See findgroups and also grpstats and splitapply

回答 (1 件)

Mehmed Saad
Mehmed Saad 2020 年 5 月 7 日
編集済み: Mehmed Saad 2020 年 5 月 7 日
Your input and output have the same name
Change it
function [x_out,y_out] = nearInfectious2(x,y,states,radius)
Initialize a counter in the start of function and increment it whenever state is equal to "i"
For example when j is equal to 2, the condition satisfies so you should write its value at the first index of x_out and y_out and increment counter to 2 after that.
Also you can do this without for loop i,e, using logical indexing
Example
s = [1 2 1];
if i want to access 1st and 3rd index, i can use direct indexing
s([1 3])
ans =
1 1
or logical indexing
s([true false true])
ans =
1 1
and getting logic (i.e. i am accessing those values of s which are equal to 1)
s==1
ans =
1×3 logical array
1 0 1
and feeding to someother vector of same length or to itself whatever you want
s(s==1)
ans =
1 1

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by