How to do math to entirety of a vector?

1 visualizzazione (ultimi 30 giorni)
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!

Risposta accettata

Star Strider
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 = 1×14
7 6 5 4 3 2 1 21 20 19 18 17 16 15
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21 63], 'Unif',0))
desiredResult = 1×21
7 6 5 4 3 2 1 21 20 19 18 17 16 15 63 62 61 60 59 58 57
.
  3 Commenti
Star Strider
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 = 1×14
1 2 3 4 5 6 7 15 16 17 18 19 20 21
desiredResult = cell2mat(arrayfun(selectIndicies,[7 21 63], 'Unif',0))
desiredResult = 1×21
1 2 3 4 5 6 7 15 16 17 18 19 20 21 57 58 59 60 61 62 63
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))
desiredResult = 1×21
1 1 1 1 1 1 1 1 2 3 4 5 6 7 15 16 17 18 19 20 21
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
Stephen23 il 27 Set 2021
Note that the square brackets are not required, to group use parentheses (exactly as MATLAB mlint recommends).

Accedi per commentare.

Più risposte (1)

David Hill
David Hill il 25 Set 2021
[1:selectSpaces(1),diff(selectSpaces)+1:selectSpaces(2)];
  3 Commenti
Xavier Bardwell
Xavier Bardwell il 25 Set 2021
And the first number is not always 7
David Hill
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

Accedi per commentare.

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by