Vector Length Error when Calling Function
이전 댓글 표시
function data = sandwichSummary(filename)
data = readcell(filename)
data(1,end+1) = {'PPI'}
length = data(2:end,2)
length = cell2mat(length)
price = data(2:end,3)
price = cell2mat(price)
PPI = round(price./length,2)
data(2:end,4) = num2cell(PPI)
avg_PPI = round(mean(PPI),2)
x_values1 = 1:length(PPI)% <- line that errors !!!!
plot(x_values1,PPI,'gd')
hold on
[max1, location1] = max(PPI)
plot(location1,max1,'rd')
[min1,location2] = min(PPI)
plot(location2,min1,'cd')
x_values2 = 1:length(PPI)
y_values(1:length(PPI)) = avg_PPI
plot(x_values2,y_values,'m-')
title('Sandwich Summary')
xlabel('Menu Item')
ylabel('Prices')
end
When I try to call this function, it errors on the line that I noted above. The error message says, "Array indices must be positive integers or logical values". I am thoroughly confused on what that means because I have never had this problem before, and I use the "length" function quite frequently. Just for reference, I have included a screenshot of what is stored in the PPI variable. It is of type double. 

답변 (2개)
You have a variable called "length":
length = data(2:end,2)
Later, on this line:
x_values1 = 1:length(PPI)
the existence of the variable "length" prevents the built-in function length from being called. Instead, MATLAB tries to index the variable "length" with index PPI, which produces the error.
The solution is to call your variable "length" something else.
You overwrite MATLAB's intrinsic "length" in the lines
length = data(2:end,2)
length = cell2mat(length)
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!