matlab 'for' loop not executing last step or single step - matlab

I don't understand why the for cycle does not execute the last cycle, i.e. the field 'PX_TO_BOOK_RATIO'.
javaaddpath('C:\DocumentsandSettings\cascari\Desktop\API\APIv3\JavaAPI\v3.7.1.1\lib\blpapi3.jar')
connection = blp;
FileName='ScopeEconomies';
list={'OPM LN Equity';'FCTY US Equity';'FCCY US Equity'}
bbgfields={'TOT_LOAN_TO_TOT_ASSET'; 'PX_TO_BOOK_RATIO' };
nfields=length(bbgfields);
for i=1:nfields
[data,sec] = history(connection, list, bbgfields(i), '01/01/1993', '12/31/2013',...
{'quarterly','all_calendar_days','nil_value'},'USD');
temp=[data{:,:}];
eval([char(bbgfields(i)) '=temp']);
name=char(bbgfields(i));
xlswrite(FileName, temp, name, 'B1');
end;
When instead I leave only one element in bbgfields, I get
Attempted to access j(1); index out of bounds because numel(j)=0.
Error in blp/history>eventHandler (line 417)
outInd(i) = j(1);
Error in blp/history (line 245)
[d,sec] = eventHandler(b,s,f);

I am guessing it is because you are using a cell as an input into history. Have you tried converting it to char as follows?
[data,sec] = history(connection, list, char(bbgfields(i)), '01/01/1993', '12/31/2013',...
{'quarterly','all_calendar_days','nil_value'},'USD');

Related

'pie' function in MATLAB gives "undefined function 'cos'" error

I wrote a function, wins_plot, to read the scoreboard from a file and store the player's name, number of plays, wins, & losses. I stored all those using struct. I loop over the file, store each line in line, textscan for everything I need from line, and then iterate i (initially == 1) as I go to expand my array of structures. A snippet from the code to represent what I am saying:
c = textscan(line, '%s %s %d %d %d');
player(i).firstName = c{1};
player(i).lastName = c{2};
player(i).plays = c{3};
player(i).wins = c{4};
player(i).losses = c{5};
After all the file has been scanned and stored, I then write this code to extract the number of wins of each player and store it in X and then finally use the pie function to represent the values in X
for n=1:(i-1)
X(n) = player(n).wins;
end
pie(X);
I get a wall of error after:
Undefined function 'cos' for input arguments of type 'int32'.
Error in pol2cart (line 22) x = r.*cos(th);
Error in pie (line 99)
[xtext,ytext] = pol2cart(theta0 + x(i)*pi,1.2);
Error in wins_plot (line 30) pie(X);
I have no clue what might be wrong. Any help would be greatly appreciated. Please keep in mind that I only just started learning MATLAB today so my knowledge of it is very limited (and I have R2013a). Thank you in advance!
The numbers got read as int32, but when you call pie, it requires them to be double to do the computation. So, when you call pie, try casting the values to double. Try this,
pie(double(X));

How to fix error: "A(I): index out of bounds; value 1 out of bound 0"

So I made this function, but I don't know why I'm getting this error. How can I fix it?
error: LOADC: A(I): index out of bounds; value 1 out of bound 0
error: called from
LOADC at line 15 column 13
function res=LOADC(url)
[nomeFicheiro,sucesso]= urlwrite(url,'Composicoes.txt');
ficheiro=fopen(nomeFicheiro,'r');
fgetl(ficheiro);
nLinhas=0;
while (fgets(ficheiro) ~= -1)
nLinhas = nLinhas+1;
end
for i=2:nLinhas
linha=fgetl(ficheiro);
pontovirgula=findstr(linha,';');
Material=linha(1:pontovirgula(1)-1);
for n=1:2:length(pontovirgula)
ElemX=linha(pontovirgula(n)+1:pontovirgula(n+1)-1);
PercentX=linha(pontovirgula(n+1)+1:pontovirgula(n+2)-1);
end
end
fclose(ficheiro);
res=Composicoes;
end
The immediate is you're trying to access a value within an empty array (which has no values in it).
The reason that this is happening is that you read your entire file inside of your first while loop which places the file pointer at the end of the file. Then (without resetting the file pointer), you try to read it line by line in the for loop. Since the file pointer is at the end of the file already, fgetl will always return an empty array ([]) so when you start trying to work with it, you get the indexing error that you've shown.
The solution is one of two options:
Call frewind(ficheiro) before the for loop to reset the file pointer to the beginning of the file so that you can successfully read each line.
Come up with a better way to parse your file rather than looping through the whole file for the sole purpose of counting the number of lines in the file.
If you post some of the file contents we can likely provide you with a better way to parse the file in one or two lines of code.
Update
Also if you look at this line, n goes all the way to the end of pontovirgula.
for n = 1:2:length(pontovirgula)
But then you try to access 1 and 2 past the end of the array
pontovirgula(n+1)
pontovirgula(n+2)
This is going to cause issues for sure. Try only looping until 2 from the end instead.
for n = 1:2:(numel(pontovirgula) - 2)
Update 2
Given that you have posted the file contents, here is an alternate way to parse the file.
fid = fopen('filename.txt', 'rt');
lines = textscan(fid, '%s', 'HeaderLines', 1);
fclose(fid);
% For each line we want to get the reference off of the front
parts = regexp(lines{1}, ';', 'split');
materials = cell(1, numel(parts));
elements = cell(1, numel(parts));
percentages = cell(1, numel(parts));
for k = 1:numel(parts)
% Remove the last empty blank
parts{k}(end) = [];
% Get the material (the first element)
materials{k} = parts{k}{1};
% Get the elements
elements{k} = parts{k}(2:2:end);
% Get the percents
percents{k} = parts{k}(3:2:end);
end
Check the length of linha, and the values of pontovirgula that you are using to index into linha.

What is "index should be positive integer(not complex format integer)" in MATLAB?

// I made function like this:
function y = ZL(L,f)
if isvector(f)
y=1j*2*pi.*f*L;
else
y=1j*2*pi.*f*L;
end
// and command :
L = 10,
f= -10000:100:10000,
ZL=ZL(L,f);
// then error :
index should be positive integer(not complex format integer) or boolean
-> this error is translated by me who is Korean; sorry
what's wrong with it?
First time you call ZL = ZL(L,f), you don't get any error.
If you try to call your command a second time, you'll get this error: Index exceeds matrix dimensions. It's because you affect the variable ZL, so the second time it's not the function you're calling but you"re trying to get elements from the array ZL.
So please don't use same name for a variable and an existing function, otherwise the function name is masked by the variable.

Looping through documents in matlab

I am attempting to loop through the variable 'docs' which is a cell array that holds strings, i need to make a for loop that colllects the terms in a cell array and then uses command 'lower' and unique to create a dictionary.
Here is the code i've tried sp far and i just get errors
docsLength = length(docs);
for C = 1:docsLength
list = tokenize(docs, ' .,-');
Mylist = [list;C];
end
I get these errors
Error using textscan
First input must be of type double or string.
Error in tokenize (line 3)
C = textscan(str,'%s','MultipleDelimsAsOne',1,'delimiter',delimiters);
Error in tk (line 4)
list = tokenize(docs, ' .,-');
Generically, if you get an "must be of type" error, that means you are passing the wrong sort of input to a function. In this case you should look at the point in your code where this is taking place (here, in tokenize when textscan is called), and doublecheck that the input going in is what you expect it to be.
As tokenize is not a MATLAB builtin function, unless you show us that code we can't say what those inputs should be. However, as akfaz mentioned in comments, it is likely that you want to pass docs{C} (a string) to tokenize instead of docs (a cell array). Otherwise, there's no point in having a loop as it just repeatedly passes the same input, docs, into the function.
There are additional problems with the loop:
Mylist = [list; C]; will be overwritten each loop to consist of the latest version of list plus C, which is just a number (the index of the loop). Depending on what the output of tokenize looks like, Mylist = [Mylist; list] may work but you should initialise Mylist first.
Mylist = [];
for C = 1:length(docs)
list = tokenize(docs{C}, ' .,-');
Mylist = [Mylist; list];
end

'Undefined function or variable' in Matlab

Here is my code:
function [im,sindx,end1]=alln(im,i,j,secret,sindx,end1)
slen=length(secret);
p=im(i,j);
neigh= [im(i-1,j) im(i+1,j) im(i,j-1) im(i,j+1) im(i-1,j-1) im(i+1,j-1) im(i-1,j+1) im(i+1,j+1)];
minpix = min (neigh)
maxpix = max (neigh)
if minpix < p < maxpix
lowlim = minpix+1;
highlim = maxpix-1;
range = highlim-lowlim+1;
nbits=floor(log2(abs(range)));
if sindx+nbits-1>slen
end1=1;
return
end
for k=1:nbits
bin(k)=secret(sindx+k-1);
end
b = bin2dec(bin);
newvalue1 = abs (minpix + b);
newvalue2 = abs (maxpix - b);
if abs(p-newvalue1)<= abs(p-newvalue2)
im(i,j) = newvalue1;
else
im(i,j) = newvalue2;
end
sindx=sindx+nbits;
end
end
My main program calls this function. When I run the program, I get the following error message:
??? Undefined function or variable "bin".
Error in ==> alln at 34
b = bin2dec(bin);
I know there are many experts for whom this is not a problem at all. I am new to MATLAB. Please guys, show me the way, which type of modification in the code can overcome this problem?
First of all, are there some lines missing from the file? Perhaps you've stripped some comments from the top? Because the error message says that
b = bin2dec(bin);
is line 34, but it's line 22 in the code you present.
OK, that aside...
The error message says that 'bin' isn't defined, but I see that it's being set on the line...
bin(k)=secret(sindx+k-1);
That suggests to me that THAT line isn't being run.
I see that that bin = ... line is inside of a 'for' loop, so I suspect that the for loop is run zero times, meaning that 'bin' never gets defined. What is nbits? Is it 1, or perhaps less than 1? THAT would prevent the loop from running at all.
Try removing the semicolon from the end of the
nbits=floor(log2(abs(range)));
line and run your code again.
Leaving off the semicolon will force the value of nbits to be printed in the Command Window. I bet you'll find that it's 1 or less. If that's the case, then start looking at HOW nbits is calculated, and I bet you'll find the problem.
At what input arguments to the function alln, are you getting the error?
Lets suppose that nbits is 0, then the following loop will not run:
for k=1:nbits
bin(k)=secret(sindx+k-1);
end
So, bin will be undefined. So, the error happens. This is one of the cases where the error can happen. There are many such possible cases.