Error : In an assignment A(:) = B, the number of elements in A and B must be the same, used in homework equation. Please help me figure out how to solve.

조회 수: 2(최근 30일)
Kristin Aldridge
Kristin Aldridge 2021년 9월 28일
답변: Geoff Hayes 2021년 9월 29일
1) For each fish, you want to find the mean of each row and store that number in a vector. You try this:
for i =1:length(rows)
m = mean(fish(i,:));
mean(i) = m;
end
You get this error:
In an assignment A(:) = B, the number of elements in A and B must be the same.
What's the easiest way to make this work?
a. Rename your vector so it doesn't conflict with the name of a built-in function
b. Try a while loop instead of a for loop
% My thought is that m = is a fine vector, because it isn't a built-in function, and neither is mean(i) = . I don't know enough about while loops to really answer this, we only just learned them today. I'm not sure how it would work if something needs to change in a while loop, since the data is constant, if that makes sense.
I tried working through it by creating my own data.
FishvsDays
Days 1 Days 2 Days 3
"Fish1" 4 3 6
"Fish2" 3 7 9
So Imported that as a column vector and a numeric matrix, because I wasn't sure exactly which to use, and ran the code...
Day1=[4;3]
Day2=[3;7]
Day3=[6;9]
%I tried Days=(Day1,Day2,Day3)
%but I get the error
Days=(Day1,Day2,Day3)
Invalid expression. When calling a function or
indexing a variable, use parentheses.
Otherwise, check for mismatched delimiters.
%so I tried made Days=(FishVsDays).
for i =1:length(Days)
m = mean(Days(i,:));
mean(i) = m;
end
%but I get the error
Error using tabular/length (line 212)
Undefined function 'LENGTH' for input
arguments of type 'table'. Use the height,
width, or size functions instead.
%I'm not sure what's going on anymore. Any help is appreciated.

채택된 답변

Geoff Hayes
Geoff Hayes 2021년 9월 29일
Kristin - you may be overconplicating it. You say that My thought is that m = is a fine vector, because it isn't a built-in function, and neither is mean(i) = but that isn't entirely true. Igoring the = sign, it is okay to name your array/vector m (though this isn't very descriptive) since it doesn't conflict with any built-in function. However, in the mean(i) you are using i to index into the array named mean which does conflict with the MATLAB function of the same name.
So you need to ask yourself, would the problem be fixed if you
a. Rename your vector so it doesn't conflict with the name of a built-in function
b. Try a while loop instead of a for loop
Note that you could replace the for loop with a while loop but would that solve the problem/error?

추가 답변(0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by