- Chapter 4 - vectors and matrices
- Chapter 5 - indexing
- Chapter 6 - array calculations
- Chapter 11 - importing data
- Chapter 12 - programming (incorporating conditional logic (if statement) and looping (for loop)
How to run a loop for variables satifying a specific condition and multiply them by values stored in a matrix?
2 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
Cris LaPierre
2020 年 3 月 22 日
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
3 件のコメント
Cris LaPierre
2020 年 3 月 23 日
編集済み: Cris LaPierre
2020 年 3 月 23 日
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) + data.delta(h);
end
ii = ii+1;
else
ii = 0;
data.new_vector(h)= data.SP(h);
end
end
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!