How to do math to entirety of a vector?
1 view (last 30 days)
Show older comments
Xavier Bardwell
on 25 Sep 2021
Commented: Stephen23
on 27 Sep 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 Comments
Accepted Answer
Star Strider
on 25 Sep 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 Comments
Star Strider
on 27 Sep 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
on 27 Sep 2021
Note that the square brackets are not required, to group use parentheses (exactly as MATLAB mlint recommends).
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!