Filter löschen
Filter löschen

Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Calculating values using for loops

2 Ansichten (letzte 30 Tage)
Jose Grimaldo
Jose Grimaldo am 7 Mär. 2020
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
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

Antworten (1)

Ameer Hamza
Ameer Hamza am 7 Mär. 2020
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

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by