# Arranging variable ranges into a cell MATLAB

I have the following simple code

v=[];

for i=10:-1:1
for j=0:0.2:5
v(end+1)=i+j;
end
end
min(v)


It returns the minimum of vector $v$ whose length in this case is 260. I would like the code to return the values of $i$ and $j$ that produce the minimum value of $v$. I defined

a=cell(2,2)


and I included the statement in the code

a{end+1,end+1}=[i j];
b=reshape(a,1,length(i)*length(j))
for k=1:length(v)
if v(k)==min(v)
disp(b{1,k})
end
end


But it didn't work.

• Logic in the code is wrong then error is because cell dimension of a and be should be comparable to use reshape command {code : b=reshape(a,1,length(i)*length(j))}. You should store the index element in separate array to get the index code. Then the code will be easy for you – AGN Jul 18 '15 at 1:25
• @ArunGovindNeelanA For the record: Since the question is purely about Matlab programming, and not about how to use Matlab to solve a scientific problem, it's actually somewhat off-topic on this site (and properly belongs on StackOverflow). Nevertheless, since the problem has been solved, would one of you post the solution as an answer so it can be accepted and the question marked as "answered"? – Christian Clason Jul 18 '15 at 8:08
• @ Christian Clason, Sir done. – AGN Jul 18 '15 at 10:48

you just need to add output to your min() function, e.g.:

[value, ind] = min(v)


ind is then the index values of your min locations (the i,j that you are looking for) and value has the corresponding min values

here I'm making some correction in that code and logic. $i$ and $j$ in matlab are reserved for complex numbers so please avoid that as much as possible in your variable name. My first code uses the advantage of matlab built in command to find the values.

clc
clear all
i1=10:-1:1;
j1=0:0.2:5;
v=zeros(1,length(i1)*length(j1));
k=1;
for ii=1:1:length(i1)
for jj=1:1:length(j1)
v(k)=i1(ii)-j1(jj);
k=k+1;
end
end

v1=[reshape(v,length(j1),length(i1))]';
[M,I] = min(v1(:));
[I_row, I_col] = ind2sub(size(v1),I);
disp('requied i_value is')
disp(i1(I_row))
display('requied j_value is')
display(j1(I_col))


Second code will give all the values of $i$ and $j$ corresponding to minimum value of $v$. This logic can be used in other programming languages.

clc
clear all
i1=10:-1:1;
j1=0:0.2:5;
v=zeros(1,length(i1)*length(j1));
k=1;
for ii=1:1:length(i1)
for jj=1:1:length(j1)
v(k)=i1(ii)-j1(jj);
k=k+1;
end
end
k=1;
for ii=1:1:length(i1)
for jj=1:1:length(j1)
if v(k)==min(v)
disp('requied i_value is')
display(i1(ii))
display('requied j_value is')
display(j1(jj))

end
k=k+1;
end
end