How to Update value of some matriks element with looping?

1 回表示 (過去 30 日間)
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 27 日
編集済み: Les Beckham 2020 年 3 月 28 日
I have condition for my matrix. Matrix x1,x2, and y. When element of y is less than 10, the y element will update will sum of x1 and x2 until the element is 10 or more. This is my code.
clc;
clear;
x1=[1 2 3 4 5 6 7 8 9 10];
x2=[1 2 3 4 5 6 7 8 9 10];
y=[10 9 11 10 11 11 9 10 12 12];
while y<10
y=x1+x2;
end
y
And then, if the problem obove is clear. I want to know how many sum (in this case, how many iteration) to achieve values of 10 or more of each element
  4 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 3 月 27 日
編集済み: Ameer Hamza 2020 年 3 月 27 日
You said it make all elements of y 10 or more but then you said
[10 9 11 10 11 11 9 10 12 12] become [10 12 11 10 11 11 9 10 12 12]
The second vector still has 9.
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
Yeah. But it's only an example. y(7) will be update to, some ways with y(2). So the vector will get [10 12 11 10 11 11 14 10 12 12]

サインインしてコメントする。

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 3 月 28 日
Try this:
x1=[1 2 3 4 5 6 7 8 9 10];
x2=[1 2 3 4 5 6 7 8 9 10];
y=[10 9 11 10 11 11 9 10 12 12];
k = 10;
x12 = x1 + x2;
mask = y < k;
y(mask) = ceil(k./x12(mask)).*x12(mask);
Result:
y =
10 12 11 10 11 11 14 10 12 12
  2 件のコメント
Eddy Iswardi
Eddy Iswardi 2020 年 3 月 28 日
thank you
Les Beckham
Les Beckham 2020 年 3 月 28 日
編集済み: Les Beckham 2020 年 3 月 28 日
For this part of your question: "I want to know how many sum (in this case, how many iteration) to achieve values of 10 or more of each element", the "iterations" required are given by this part of Ameer's excellent answer:
ceil(k./x12(mask))
If you do this:
iterations = zeros(size(x1));
iterations(mask) = ceil(k./x12(mask))
you will get a vector showing the number of sums required for every element of your original vector with zeros where no iterations (sums) were required.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by