简体   繁体   English

循环以重新分配矢量元素Matlab

[英]Loop to reassign vector elements matlab

In Matlab, I have a vector A of size 30x1 and another vector B of size 3x1. 在Matlab中,我有一个大小为30x1的向量A和另一个大小为3x1的向量B

  A = [1.23 2.2 3.3 4.8 5.1 6.7 7.1 8.2 9.9 10.25 11.00 12.1 13.2 14.3 15.4 16.5 17.5 18.1 19.8 20.188 21.2 22.4 23.6 24.1 25.2 26.7 27.8 28.2 29.1 30.3]';

  B = [1.23 10.25 20.188];

I want to create a vector C of the same size as A from A and B such that 我想从AB创建与A大小相同的向量C

  C = [2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2]';

The numbers in B are times that are the exact same as elements in A , some elements apart, for eg B(2)=A(10) . B中的数字是与A元素完全相同的时间,相隔一些元素,例如B(2)=A(10)

Now I need to write a loop such that every time the loop sees the same number in B as in A it writes 2 to C until it finds the next element of B which is the same as A where it will then write 1 until it finds the next same element. 现在我需要编写一个循环,使得每次循环看到在相同数量的BA写入2至C,直到它找到的下一个元素B这是一样的A在那里它将然后写1 ,直到找到下一个相同的元素。

So for eg 所以例如

  B(1) = 1.23 and A(1) = 1.23 so C(1:i,1)=2; %where i is the index of the 
next similar element. 

Can anyone help me as to how to write this loop exactly? 谁能帮我准确地编写此循环吗? I need to make the loop general so not assuming anything about where the positions of the same elements are or could be because I could have different sized vectors (when I need to implement this later in a script). 我需要使循环通用化,以免假设相同元素的位置在哪里或可能在何处,因为我可以使用不同大小的向量(当我稍后需要在脚本中实现此功能时)。

Thanks!! 谢谢!!

You can start by finding the indices. 您可以从查找索引开始。 Try the following: 请尝试以下操作:

locs = find(ismember(A, B)) % This will give you the required indices
N = numel(locs);

% Pre-allocate the C vector
C = zeros(size(A)); 
L = numel(C);

if ~mod(N, 2)
   C(locs(N):L) = 1;
else
   C(locs(N):L) = 2;
end

% Now start the loop
for i = 1:N-1
    if ~mod(i,2)
       C(locs(i):locs(i+1)-1) = 1;
    else
       C(locs(i):locs(i+1)-1) = 2;
    end
end

Hope this helps. 希望这可以帮助。 You can add error handling to it and find ways to shorten the code. 您可以为其添加错误处理,并找到缩短代码的方法。

How about a vectorized one-liner: 向量单线如何:

mod(cumsum(ismember(A,B)),2)+1

No need for loops on this one 无需在此循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM