Multiport switch with code
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Zack Peters
le 24 Oct 2013
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Function Creation dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!