Array indices must be positive integers or logical value when read images in matlab - matlab

trying to read multi images in matlab in loop so error Array indices must be positive integers or logical values is appear
for i=1:12 % we have 16 images we have in or folder
clc;clear;
images ='/home/mohamed/Downloads/Lab6-20200415/Lab6-20200421/Lab6/Lab6/';
jpgfiles=dir(fullfile(images,'\*.jpg*'));
n=numel(jpgfiles(i));
im=jpgfiles(i).name;
im1=imread(fullfile(images,im));
d1 = rg2gray(iml);
imshow(im1);
end

Here is a minimal example demonstrating your problem:
for i=1:10
clear
jpgfiles=rand(10,1); %some dummy data to replace your actual code
jpgfiles(i);
end
the clear deletes the variable i which means i is the imaginary unit, not a valid index. Avoid the variable name i, it leads to difficult to debug problems. With other variable names, the much clearer error message would have been:
Unrecognized function or variable 'ix'.
Error in foo (line 4)
jpgfiles(ix);

Related

Receiving unknown errors when trying to use fsolve to find the solutions of a function

I have to plot the solution for masses between 4 and 8kg, which I wrote using the code below:
weight=linspace(4,8,100)
Then I use a for loop to find the solutions for the weights within this vector, while also declaring the variable a, and a guess of the time required:
for z=1:length(weight)
a=(weight./(1360*pi)).^(1/3)
tguess=14400
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
timeinhours=timeinseconds/(60*60)
end
The function that I mentioned previously is below:
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*((alpha.*t))./(a.^2)))-57/80
end
Where F(1) represents the following equation 1, which will be equal to 57/80. Rather than adding until infinity, I chose the value of 22 as the equation converges to this value. r/a is equal to 0.464, which is why this is present within my function.
When running this code, I am given errors that I cant manage to solve.
Arrays have incompatible sizes for this operation.
Error in Homework1>cookingtimes (line 58)
F(1)=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).*(pi.^2).*.((alpha.*t))./(a.^2)))-57/80
Error in Homework1 (line 28)
timeinseconds=fsolve(#(t)cookingtimes(t,a),tguess)
Error in fsolve (line 264)
fuser = feval(funfcn{3},x,varargin{:});
Caused by:
Failure in initial objective function evaluation. FSOLVE cannot continue.
The arrays that I have produced are all of the same length, which is why I am very stuck on this issue.
You are trying to perform an operation on two arrays that have different sizes. In your case, the issue may be caused by the fact that you are defining the variable a as a vector inside the for loop, but using it in the function cookingtimes as a scalar. To fix this, you can modify your function to accept a vector of a values and return a corresponding vector of function values.
I modified the cookingtimes function to accept a vector of a values, and return a corresponding vector of function values.
function F=cookingtimes(t,a)
k=1:22;
alpha=0.7*10^(-7);
F=(2./(pi*0.464))*sum(((-1).^(k-1))./k).*sin(k*pi*0.464).*exp(((-(k.^2)).* (pi.^2).*((alpha.*t))./(a.^2)))-57/80;
end
In the for loop, You need to compute a for each weight value, and use a vector of a values in the call to fsolve. Also store the solutions in a vector timeinseconds instead of a scalar, as there are multiple solutions to be found.
for z=1:length(weight)
a=(weight(z)./(1360*pi)).^(1/3); % compute a for each weight value
tguess=14400;
timeinseconds(z)=fsolve(#(t)cookingtimes(t,a),tguess);
timeinhours=timeinseconds/(60*60);
end

MATLAB: Using FZERO on a function which has a vector output

I am working on my thesis and running in some programming problems in Matlab. I am trying to implement the ''golden Bisection Method'' to speed up my code. To this end, I've consulted the build in function FZERO.
So I am determining the difference between two vectors which are both (1x20).
Difference = Clmax_dist-cl_vec;
Clmax_dist comes from a semi-empirical method and cl_vec comes from the excecution of an external AVL.exe file.
Essentially, this difference depends only on one single variable AOA because the Clmax_dist vector is a constant. Hence, I am constantly feeding a new AOA value to the AVL.exe to obtain a new cl_vec and compare this again to the constant Clmax_dist.
I am iterating this until one of the element in the vector becomes either zero or negative. My loop stops and reveals the final AOA. This is a time consuming method and I wanted to use FZERO to speed this up.
However, the FZERO documentation reveals that it only works on function which has a scalar as input. Hence, my question is: How can I use FZERO with a function which has a vector as an output. Or do i need to do something totally different?
I've tried the following:
[Difference] = obj.DATCOMSPANLOADING(AOA);
fun=#obj.DATCOMSPANLOADING;
AOA_init = [1 20];
AOA_root = fzero(fun,AOA_init,'iter');
this gave me the following error:
Operands to the || and && operators must be convertible to logical scalar values.
Error in fzero (line 423)
while fb ~= 0 && a ~= b
Error in CleanCLmax/run (line 11)
AOA_root = fzero(fun,AOA_init,'iter');
Error in InitiatorController/moduleRunner (line 11)
ModuleHandle.run;
Error in InitiatorController/runModule (line 95)
obj.moduleRunner(ModuleHandle);
Error in RunSteps (line 7)
C.runModule('CleanCLmax');
The DATCOMSPANDLOADING function contains the following:
function [Difference] = DATCOMSPANLOADING(obj,AOA)
[Input]= obj.CLmaxInput; % Creates Input structure and airfoil list
obj.writeAirfoils(Input); % Creates airfoil coordinate files in AVL directory
[Clmax_dist,YClmax,Cla_mainsections] = obj.Clmax_spanwise(Input); % Creates spanwise section CLmax with ESDU method
[CLa] = obj.WingLiftCurveSlope(Input,Cla_mainsections); % Wing lift curve slope
[Yle_wing,cl_vec] = obj.AVLspanloading(Input,CLa,AOA); % Creates spanloading with AVL
Difference = Clmax_dist-cl_vec;
end
If I need to elaborate further, feel free to ask. And of course, Thank you very much.
fzero indeed only works on scalars. However, you can turn your criterion into a scalar: You are interested in AOA where any of the elements in the vector becomes zero, in which case you rewrite your objective function to return two output arguments: minDifference, which is min(Difference), and Difference. The first output, minDifference is the minimum of the difference, i.e. what fzero should try to optimize (from your question, I'm assuming all values start positive). The second output you'd use to inspect your difference vector in the end.

How can I apply Huffman coding correctly?

I applied the zigzag function after quantization to an image block, and I want to compute the Huffman coding of this block. I understand that the input argument must be a vector, and that the histogram should be calculated.
I wrote the following code, but it doesn't seem to work:
[M N]=size(yce);
fun1=zigzag(yce);
count1 = imhist(fun1);
p1 = count1/ numel(fun1);
[dict1,avglen1]=huffmandict(count1,p1);
comp1= huffmanenco(fun1,dict1);
Im1 = huffmandeco(comp1,dict1);
I get the following error with the huffmandict function:
Error in project at 65
[dict1,avglen1]=huffmandict(count1,p1);
Source symbols repeat.
zigzag.m is a written function in a matlab file.it converts a matrix into a vector,thus eliminating long sequences of zeros.
The Huffman encoding function (huffmandict) in MATLAB requires that the symbols vector (first argument of the function) must all be unique values. This symbols vector is a list of all possible symbols that are seen in your data that you want to encode / compress. As such, it wouldn't make sense to have a list of all symbols to be encountered if there are duplicates. This is much like a dictionary of words, where it wouldn't make sense to see the same word twice in this dictionary. The second parameter of the function is the associated probabilities of occurrence for each symbol in your sequence.
With huffmandict, what you are doing is you are creating a dictionary for Huffman encoding that consists of all possible unique symbols to be encountered when encoding/decoding as well as their associated probabilities. Therefore, by examining your code, you need to extract both the bin locations as well as the probabilities of occurrence when using imhist. Essentially, you need to call the two element output version of imhist. The second output of imhist gives you a list of all possible intensities / symbols that were encountered in the data, while the first element gives you the frequency of each these intensities / symbols in your data. You then normalize the first output element by the total number of symbols / intensities in your data to get the probabilities (assuming equiprobable encounters of course). Once this is complete, you use both of these as input into huffmandict.
In other words, you need to change only two lines of code, thus:
[M N]=size(yce);
fun1=zigzag(yce);
[count1,x] = imhist(fun1); %// Change
p1 = count1/ numel(fun1);
[dict1,avglen1]=huffmandict(x,p1); %// Change
comp1= huffmanenco(fun1,dict1);
Im1 = huffmandeco(comp1,dict1);
Edit
Knowing how fun1 is structured now, do not use imhist. imhist assumes that you are putting in image data, but it doesn't look like that's the case. Instead, try using histc instead to compute the frequency of occurrence. As such, simply modify your code to this:
[M N]=size(yce);
fun1=zigzag(yce);
bins = unique(fun1); %// Change
count1 = histc(fun1, bins); %// Change
p1 = count1/ numel(fun1);
[dict1,avglen1]=huffmandict(bins,p1); %// Change
comp1= huffmanenco(fun1,dict1);
Im1 = huffmandeco(comp1,dict1);
unique finds those unique values that are in your vector so that we can use these as bins to calculate our frequencies. This also figures out the all possible symbols seen in the data.

How to pass integers in a loop using MATLAB

I am trying to run the following code:
%% Getting Stocks
stocks = hist_stock_data('01012013','07112014','GDXJ', 'SPY','GOOGL', 'QQQ', 'AAPL');
%% Loop to get the stocks in order by date
while i <= 5
stocks(1,i).Date=datenum(stocks(1,i).Date);
stocks(1,i).Date = stocks(1,i).Date(end:-1:1);
stocks(1,i).AdjClose = stocks(1,i).AdjClose(end:-1:1);
stocks(1,i).Ticker =stocks(1,i).AdjClose;
end
However I am getting the following error:
Subscript indices must either be real positive integers or logicals.
I have searched the web but do not really understand why I am getting this error?
First off, you must have mentioned that hist_stock_data is a function that you got from an external source and isn't a MATLAB builtin function or variable. Well, I googled for it and found it on MATLAB File Exchange.
Next up looking at the code, here's some advice - Try to avoid using i as an iterator because when uninitialized MATLAB would consider it as the imaginary unit. Read more about it here. That's why you were getting that error - Subscript indices must either be real positive integers or logicals., because the index being used was the imaginary unit that can't be used as an index.
So, we could change i to something like ii -
while ii <= 2
stocks(1,ii).Date=datenum(stocks(1,ii).Date);
stocks(1,ii).Date = stocks(1,ii).Date(end:-1:1);
stocks(1,ii).AdjClose = stocks(1,ii).AdjClose(end:-1:1);
stocks(1,ii).Tiicker =stocks(1,ii).AdjClose;
end
Then, we run the code and see this error -
Undefined function or variable 'ii'.
Now, I made some guesswork and replaced that while-loop with a for-loop that iterates for all the elements in the struct stocks. So, it becomes -
for ii = 1:numel(stocks)
stocks(1,ii).Date=datenum(stocks(1,ii).Date);
stocks(1,ii).Date = stocks(1,ii).Date(end:-1:1);
stocks(1,ii).AdjClose = stocks(1,ii).AdjClose(end:-1:1);
stocks(1,ii).Tiicker =stocks(1,ii).AdjClose;
end
This runs fine, but make sure the results are what you were looking to have in stocks.
If you were looking to run the loop for the first 5 elements only, then do this -
for ii = 1:5

In Matlab, error using length(x), gives subscript indicies error

Im extracting time-dependent data from a .dat file, and using the spline function, matching the values to an existing time-vector in use. For some reason the length function is failing to read the length of the vector.
I can recreate the error with this blurb:
x = linspace(1,98,76)';
y = 20.*x-5.*x.^2;
t = linspace(0,100,1000)';
yy = spline(x,y,t);
length(yy)
It returns
??? Subscript indices must either be real positive integers or logicals.
It shows in my workspace that yy is 1000x1 double, and max(size(yy)) works fine. Any idea on what creates this error?
You probably have a variable named length in your workspace. Use the whos command to see if this is the case.
whos length
This will print out the size and type of the variable length if it exists.