Multiport switch with code
4 次查看(过去 30 天)
显示 更早的评论
Hello,
I am trying to create a multiport switch with code. I have a control vector and 40 other vectors stored as one matrix (called data). The control vector denotes which of the 40 data vectors to pass through. All 41 of these vectors (control and 40 data vectors columns) have the same number of elements. So ultimately, I would like to create one vector with chunks from each of the 40 data vectors (dependent on what the control vector specifies). Another user suggested doing this by indexing but I don't completely understand his code (found below). Any help would be greatly appreciated. I'm very new to indexing and could use any information provided.
Thanks in advance.
Btw, this is a sample control stream. My actual one is immense but I have limited it to 20000 elements so a method that does this faster than a for loop (if possible) would be great.
ControlStream = [0 1 1 3 2 3 3 1 4 1 5 5 6 4 7 9 8 2 9 1 10 1];
newStream = [];
startindex = ControlStream(1:2:end);
endindex = startindex+10;
streamNum = ControlStream(2:2:end);
for i = 1:length(startindex)
newStream = [newStream DataMatrix(startindex(i):endindex(i),streamNum(i))];
end
0 个评论
采纳的回答
Zack Peters
2013-10-24
Hi Muneer,
Thanks to advances in the MATLAB execution engine, for loops such as the one above are really quite efficient. However, with that being said there definitely a way to get this done via indexing which is marginally faster. You can first convert the subscripts (I,J) that you want to pull from your data matrix into linear indices by using the SUB2IND function. From there, you can simply grab only the linear indices that you want from the giant data matrix (40x20000 elements).
control_vect = randi([1,40],1,20000);
data = rand(40,20000);
a = tic;
my_output1 = zeros(1,length(control_vect));
for i = 1:length(control_vect)
my_output1(i) = data(control_vect(i),i);
end
toc(a)
b = tic;
linearInd = sub2ind(size(data),control_vect,1:length(control_vect));
my_output2 = data(linearInd);
toc(b)
isequal(my_output1,my_output2)
By running the above script, you will see from the tic/toc wrapped around each sections of code that the time is very low in both cases, but very clearly lower in the second case where linear indexing is used instead of the for loop. In either case, the efficiency of MATLAB is such that the difference is not noticeable.
~Zack
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!