MATLAB Answers

How to run a loop for variables satifying a specific condition and multiply them by values stored in a matrix?

1 view (last 30 days)
EM geo
EM geo on 22 Mar 2020
Edited: Cris LaPierre on 23 Mar 2020
i need to create a NEW vector in which, starting from the condition that SP > 0 i can create a new vector. In detail want to skip the first line, then I want to multiply SP by 0.1 (position h+1), then 0.4 for h+2, then 0.5 for h+3 , summing the corresponding delta. You can see an example in the figure attached.
Anyone can help me?
I attached my data
Thanks in advance!


Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 22 Mar 2020
I recommend you spend some time going through MATLAB Onramp. It's interactive, and you can go at your own pace. Oh, and it's free.
In particular, focus on
  1. Chapter 4 - vectors and matrices
  2. Chapter 5 - indexing
  3. Chapter 6 - array calculations
  4. Chapter 11 - importing data
  5. Chapter 12 - programming (incorporating conditional logic (if statement) and looping (for loop)


EM geo
EM geo on 23 Mar 2020
@Cris LaPierre thanks for your suggestions... I tried with this but there's something wrong... Can you help me to find the error please?
m =[0.1; 0.4; 0.5];
for h = 1:numel(SP)
if SP(h) > 0
for ii = 1:length(m)
new_vector(h+ii,:) = SP(h+ii,:)*m(ii) + delta(h+ii,:)
new_vector(h,:)= SP(h,:);
Cris LaPierre
Cris LaPierre on 23 Mar 2020
Nice job! That's pretty good. The remaining issues are subtle.
I made a slight change to how the data is loaded and accessed (I use a table). This means I made a slight tweak to the counter in the first for loop. The new vector is added to the table data (appears as a 4th column).
The issue is that you pause the first for-loop while you calculate new_vector. The second for-loop moves three indices ahead (h+ii) calculating new_vector. However, once it exits, the first for-loop resumes, and its value of h picks up where it left off. This means it overwrites the values that were added by the seond for-loop. Therefore, only the 0.1*SP+delta values remain.
You might be tempted to try to modify the value of h, but any changes are ignored. MATLAB doesn't let you modify the index of a for-loop.
What I would suggest is to change the second for-loop to an if statement. Make ii a counter that is 0 when SP=0, then 1, then 2, then 3. The tricky part is placing the conditional statements, incrementing and resetting to 0 in the correct spots.
data = readtable("data.xls");
m =[0.1; 0.4; 0.5];
ii = 0;
for h = 1:height(data)
if data.SP(h) > 0
if ii > 0
data.new_vector(h) = data.SP(h)*m(ii) +;
ii = ii+1;
ii = 0;
data.new_vector(h)= data.SP(h);
You might notice this runs quicker as well. Your code was running the second for-loop for every value of SP>0. Since most of these were unnecessary, all it was doing was slowing your code down.

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Translated by