Sorting and replacing data in matlab

E
Evelyn · Dec 10, 2020 · 1.9K views
Question
I have a position Array suppose "A" A =[ 1, 0, 3, 4, 5, 6, 7, 8, 0, 0,15, 20, 10, 9]. I want to replace all those values of A which are grater than 5. Here, the first element (in A, it is 6) which is grater than 5 will be replaced by a constant say c1 Then next element (in A, it is 7) which is grater than 5 will be replaced by a constant say c2 =c1+ a, where 'a' is a constant After that the next element (in A, it is 8) which is grater than 5 will be replaced by a constant say c3 =c2+ a, where 'a' is a constant ...... So on. I want to see the final Array like this A =[ 1, 0, 3, 4, 5, c1, c2, c3, 0, 0, c4, c5, c6, c7].   N.B. if any element of A is less or equal than 5, the elements of A will be unchanged  
Expert Answer
Profile picture of Kshitij Singh
Kshitij Singh PhD Expert
Answered Aug 17, 2026

Here is a vectorized alternative:

A = [ 1, 0, 3, 4, 5, 6, 7, 8, 0, 0,15, 20, 10, 9];
a = 1; c1 = 10;
idx = A > 5;
A(idx) = c1 + (0:nnz(idx)-1)*a;

Result

>> A
A =
     1     0     3     4     5    10    11    12     0     0    13    14    15    16
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!