필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Calculating values using for loops

조회 수: 2 (최근 30일)
Jose Grimaldo
Jose Grimaldo 2020년 3월 7일
마감: MATLAB Answer Bot 2021년 8월 20일
I want to perform the following calculations using for loops. The user enters the inputs the value and the index is set. I want to calculate every index three times, since my first condition in the for loop is if idx(x) <= a(:), variable a=[2,3,4]. So the first time that it calculates the first set would be
idx(x)<=2 using B(1) C(1) and then idx(x)<=3 using B(2) C(2) and lastly idx(x)<=4 using B(3) C(3). How can i make it work using for loops?
I get an error that states 'Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.'
n=input('From zero, until what number do you want to calculate.Enter value:');
idx=0:0.1:n ;
a=[2,3,4];
B=[4,6,8];
C=[2,6,7];
v=[];
for x=1:length(idx)
if idx(x) <= a(:)
v(x)=-C.*idx(x)+B.*2;
else
v(x)=-C.*idx(x)+B.*2+(B./2).*2
end
end

답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 3월 7일
The error message is pretty self-explanatory. The dimension of -C.*idx(x)+B.*2 is 1x3, whereas you are trying to assign it to a single element of a numeric array. Without any context, the following are the few possible solutions to get rid of this error
for x=1:length(idx)
if idx(x) <= a(:)
v(x,:)=-C.*idx(x)+B.*2;
else
v(x,:)=-C.*idx(x)+B.*2+(B./2).*2;
end
end
This will create the vector v with the dimension of 101x3.
The other solution is to create a cell array
for x=1:length(idx)
if idx(x) <= a(:)
v{x}=-C.*idx(x)+B.*2;
else
v{x}=-C.*idx(x)+B.*2+(B./2).*2;
end
end

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by