Arithmetic Operation on Elements of a Vector satisfying a given condition using Logical Indexing
Show older comments
I have a problem statement where i have to change the elements of a vector depending on some condition
the vector comprises of random number between 4 to 12 i.e. 4,5,6,7,8,9,10,11,12
for eg. the given vector is A = [ 5,6,8,9,7,5,4,12,11,9,10]
now i have to add a scalar to the given vector , which can be either a -ive number or a +ive number
and any element of the resultant vector greater than 12 should be wrap around and any if the element is smaller than 4 then also it should be wrapped around.
for eg. if my input scalar is 3 , then the element 11 in input vector after addition operation will become 15 which is greater than 12
and should be wrapped around and changed to 5 , like shift in a circular manner.
in second case taking the input scalar as -4 to be added to the vector A , the element 6 will become 2 and should be wrapped around and changed to 11
I can solve this using for loop and if else statement , but i am interested in solving this via logical indexing.
any help on that will be greately appreciated.
1 Comment
ANKUR WADHWA
on 3 May 2020
Answers (1)
Ameer Hamza
on 3 May 2020
Edited: Ameer Hamza
on 3 May 2020
For first question
A = [5,6,8,9,7,5,4,12,11,9,10];
scalar = -4;
lb = 4; % lower bound
ub = 12; % upper bound
A_shift = mod((A-lb)+scalar, ub-lb+1)+lb;
Result
>> A
A =
5 6 8 9 7 5 4 12 11 9 10
>> A_shift
A_shift =
10 11 4 5 12 10 9 8 7 5 6
For second question. Correct syntax is
v(v<0) = v(v<0)-3;
6 Comments
ANKUR WADHWA
on 4 May 2020
Edited: ANKUR WADHWA
on 4 May 2020
Ameer Hamza
on 4 May 2020
Try this
A = [5,6,8,9,7,5,4,12,11,9,10];
scalar = 4;
lb = 4; % lower bound
ub = 12; % upper bound
A_ = A + scalar;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
A_shift = mod((A-lb)+scalar, ub-lb+1)+lb;
12-4+1=9 is necessary because the mod will keep the value from 0 to 9-1. If you set it to 8 then you will only get digits from 0 to 7.
ANKUR WADHWA
on 4 May 2020
Ameer Hamza
on 4 May 2020
Yes. I just added the last line as example. These lines
A_ = A + scalar;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
shows the correct way to write the function shift().
ANKUR WADHWA
on 4 May 2020
Ameer Hamza
on 4 May 2020
Also wrap the shifting factor
wrap = shift('1234', 96)
back = shift(wrap, -96)
% the bounds are 32 and 126 in this case
function coded = shift(A, b)
ub = 126;
lb = 32;
b = rem(b, ub-lb);
A_ = A + b;
A_(A_ > ub) = A_(A_ > ub) - ub + lb + 1;
A_(A_ < lb) = A_(A_ < lb) - lb + ub + 1;
coded = char(A_);
end
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!