How to do math to entirety of a vector?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Xavier Bardwell
il 25 Set 2021
Commentato: Stephen23
il 27 Set 2021
selectIndicies = [selectSpaces:-1:selectSpaces-6]
I have this line that is supposed takes a vector of N columns (selectspaces) and gives me the number of selectSpaces and the 6 numbers before it.
For example, if selectSpaces was [7 21] then i would like to get the vector [1 2 3 4 5 6 7 15 16 17 18 19 20 21], but right now all i get is [1 2 3 4 5 6 7].
How can i do this without loops?
Thanks!
0 Commenti
Risposta accettata
Star Strider
il 25 Set 2021
Creating it as an anonymolus function and using it with arrayfun and cell2mat is an option —
selectIndicies = @(selectSpaces) [selectSpaces:-1:selectSpaces-6];
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21], 'Unif',0))
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21 63], 'Unif',0))
.
3 Commenti
Star Strider
il 27 Set 2021
That would simply require changing the subscript references:
selectIndicies = @(selectSpaces) [selectSpaces-6:selectSpaces];
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21], 'Unif',0))
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21 63], 'Unif',0))
Ideally, this would need to incorporate logic to prevent non-positive indices:
selectIndicies = @(selectSpaces) [selectSpaces-6:selectSpaces].*(selectSpaces > 6)+ones(size(selectSpaces)).*(selectSpaces<6);
desiredResult = cell2mat(arrayfun(selectIndicies,[4 7 21], 'Unif',0))
So in this instance, if an argument were less than 7, the result would simply be a series of 1 signalling an inappropriate argument and preventing a subscript error. There are likely other ways to correct for out-of-range arguments, and producing different results. This is just one example.
Experiment to get the result you want.
.
Stephen23
il 27 Set 2021
Note that the square brackets are not required, to group use parentheses (exactly as MATLAB mlint recommends).
Più risposte (1)
David Hill
il 25 Set 2021
[1:selectSpaces(1),diff(selectSpaces)+1:selectSpaces(2)];
3 Commenti
David Hill
il 25 Set 2021
a=[8,26,46,100];
b=a-6;
Out=[];
for k=1:numel(a)
Out=[Out,b(k):a(k)];
end
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!