I have decided to do some repetition in Matlab during this summer so I'm doing a lot of assignments again that I have already finished a couple of months ago. Though, I stumble upon a certain assignment and my solution would be:
load tal
v_stor=[];
v_liten=[];
v_mellan=[];
for i=1:length(V)
if V(i)>=10
v_stor = v_stor + V(i);
elseif V(i)<=-10
v_liten = v_liten + V(i);
else
v_mellan = v_mellan + V(i);
end
end
v_stor
v_mellan
v_liten
I think it's pretty straightfoward what I want my code to do. This gave me empty vectors and I was confused why, so I checked my earlier solution:
load tal
t = 0;
v_stor = [];
v_mellan = [];
v_liten = [];
for i= 1:length(V)
if V(t+1)>= 10
v_stor=[v_stor V(t+1)];
elseif V(t+1)<=-10
v_liten = [v_liten V(t+1)];
else
v_mellan=[v_mellan V(t+1)];
end
t=t+1;
end
v_stor
v_mellan
v_liten
So my question is, why is my second solution wrong and how come, in my earlier solution, that I used V(t+1)? It looks the same to me.
Edit: Vector V is of size 1000x1

 채택된 답변

dipak nigam
dipak nigam 2020년 6월 29일

1 개 추천

load tal
v_stor=[];
v_liten=[];
v_mellan=[];
for i=1:length(V)
if V(i)>=10
v_stor = [v_stor V(i)];
elseif V(i)<=-10
v_liten = [v_liten V(i)];
else
v_mellan = [v_mellan V(i)];
end
end
v_stor
v_mellan
v_liten
You were trying to add values to a vector by using '+' operator. You need to change your code like above to get the desired result.

추가 답변 (1개)

KSSV
KSSV 2020년 6월 29일
편집: KSSV 2020년 6월 29일

1 개 추천

In the first case, you are not saving the result. Check the below.
load tal
v_stor=zeros(1,length(V));
v_liten=zeros(1,length(V));
v_mellan=zeros(1,length(V));
for i=1:length(V)
if V(i)>=10
v_stor(i) = V(i);
elseif V(i)<=-10
v_liten(i) = V(i);
else
v_mellan(i) = V(i);
end
end
v_stor
v_mellan
v_liten

댓글 수: 5

I fixed my error:
for i=1:length(V)
if V(i)>=10
v_stor = [v_stor V(i)];
elseif V(i)<=-10
v_liten = [v_liten V(i)];
else
v_mellan = [v_mellan V(i)];
end
end
And achieved the correct answer.
How silly of me to make that mistake. Good that I'm doing repeat of the assignments.
KSSV
KSSV 2020년 6월 29일
편집: KSSV 2020년 6월 29일
The above method takes time..the right way is what I have shown. Also you need not to use loop for your case.
v_stor = V(V>=10) ;
v_liten = V(V<=-10) ;
v_mellan = V(V>=10 & V<10) ;
Michael Peyron
Michael Peyron 2020년 6월 29일
I did not know this way of extracting the values existed. Thanks for telling. They only taught us how to do it with for loops.
KSSV
KSSV 2020년 6월 29일
The basic building block is a loop. But in MATLAB you can avoid loop most of the times....remember the full form of MATLAB.
Michael Peyron
Michael Peyron 2020년 6월 29일
Thanks! I added your code to my notes!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2020a

태그

질문:

2020년 6월 29일

댓글:

2020년 6월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by