How can call a vector element using index in the condition of if_else loop?

3 ビュー (過去 30 日間)
Sharad Patel
Sharad Patel 2021 年 6 月 7 日
編集済み: SALAH ALRABEEI 2021 年 6 月 7 日
Here in this code the R is a vector and using find I identified the indexes of specified number and save them to vectors m, n, o, p. Now by using the vector I want to fill the random numbers between 5 and 40 so I developed the following code. But I am not getting desired result.
R=P(:,6);
m =find(R==40);
n =find(R==25);
o =find(R==15);
p =find(R==8)
for k= 1:6160
if k==k.m
R(k,1)=randi([5 40],:,1);
elseif k==k.n
R(k,1)=randi([5 40],:,1);
elseif k==k.o
R(k,1)=randi([5 40],:,1);
elseif k==k.p
R(k,1)=randi([5 40],:,1);
end
end
R

採用された回答

SALAH ALRABEEI
SALAH ALRABEEI 2021 年 6 月 7 日
% Try this
R=P(:,6);
m =find(R==40);
n =find(R==25);
o =find(R==15);
p =find(R==8)
for k= 1:6160
if ismember(k,m)
R(k,1)=randi([5 40],1);
elseif ismember(k,n)
R(k,1)=randi([5 40],1);
elseif ismember(k,n)
R(k,1)=randi([5 40],1);
elseif ismember(k,n)
R(k,1)=randi([5 40],1);
end
end
R
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 6 月 7 日
So all of the R=40 should result in the same random number for all positions? And all of the 25 should result in the same random number as each other, but different from the R=40?
Sharad Patel
Sharad Patel 2021 年 6 月 7 日
it can be 40 as well

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

その他の回答 (2 件)

SALAH ALRABEEI
SALAH ALRABEEI 2021 年 6 月 7 日
編集済み: SALAH ALRABEEI 2021 年 6 月 7 日
% A faster way
R(m,1)=randi([5 40],length(m),1);
R(n,1)=randi([5 40],length(n),1);
R(o,1)=randi([5 40],length(o),1);
R(p,1)=randi([5 40],length(p),1);
  2 件のコメント
Walter Roberson
Walter Roberson 2021 年 6 月 7 日
you need
, 1
on the randi. The default with a single size parameter is square matrix.
SALAH ALRABEEI
SALAH ALRABEEI 2021 年 6 月 7 日
Absolutely right. Thank you, it will be fix to avoid confusions

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


Walter Roberson
Walter Roberson 2021 年 6 月 7 日
R=P(:,6);
m =find(R==40);
n =find(R==25);
o =find(R==15);
p =find(R==8)
k = [m;n;o;p];
nk = length(k);
R(k,1) = randi([5,40],nk,1);
  1 件のコメント
Sharad Patel
Sharad Patel 2021 年 6 月 7 日
Thank you Walter but I want only one value of random number between 5 and 40 for each condition.

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

カテゴリ

Help Center および File ExchangeConversion Between Symbolic and Numeric についてさらに検索

製品


リリース

R2012a

Community Treasure Hunt

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

Start Hunting!

Translated by