compromise the solution of multi objective function in matlab - algorithm

**I have two objective function, I optimized them in matlab using genetic algorithm multi objective function as the follow
f
unction [output]= multi_objective_function_2(input)**
x1 = input(1);
x2 = input(2);
x3 = input(3);
x4 = input(4);
x5 = input(5);
x6 = input(6);
x7 = input (7);
f1 = -(1.0125*x1 + 14.8125*x2 + 1.3113*x3 + 0.783*x4 + 10.365*x5 + 2.435*x6 + 1.78*x7);
f2 = -(3303*x1 + 7510*x2 + 41370*x3 + 1628*x4 + 23046*x5 + 5412*x6 + 58113*x7);
output = [f1 f2];
end
clear;
clc;
tic
numberOfVariables = 7;
A = [-1 0 0 0 0 0 0; 0 -1 0 0 0 0 0; 0 0 -1 0 0 0 0; 0 0 0 -1 0 0 0; 0 0 0 0 -1 0 0; 0 0 0 0 0 -1 0; 0 0 0 0 0 0 -1; 1715.78 5586.32 1654.93 1963.37 4414.64 6973.88 4416.31; -1.0125 -14.8125 -1.3113 -0.783 0 0 0];
b = [-3; -45; -2445; -71; -10402.5; -5201; -10402.5; 208000000; -3931];
Aeq = [1 1 1 1 0 0 0; 0 0 0 0 1 1 1];
beq = [26006.25; 26006.25];
LB = [0 0 0 0 0 0 0];
UB = [26006.25 26006.25 26006.25 26006.25 26006.25 26006.25 26006.25];
options = gaoptimset('PlotFcns',#gaplotpareto);
[x,fval,exitflag,output] = gamultiobj(#multi_objective_function_2,numberOfVariables,A,b,Aeq,beq,LB,UB,options);
disp(' x1 x2 x3 x4 x5 x6 x7 ');
disp(x)
disp(' F1 F2');
disp(fval)
disp(output)
fprintf('The number of points on the Pareto front was: %d\n', size(x,1));
toc
I want solution which make each of the two objective function to be achieve 50% of the solutioى

Related

How to calculate cost to Convert an N X M binary matrix to all 0 matrix with only allowed moves as square-matrix toggle?

Given an N X M binary matrix ( every element is either 1 or 0) , find the minimum number of moves to convert it to an all 0 matrix.
For converting a matrix, one can choose squares of any size and convert the value of that square. '1' changes to '0' and '0' changes to '1'.This process can be done multiple times with square of the same size. Converting any square counts as 1 move.
Calculate minimum number of moves required..
Example :
input matrix
0 1 1
0 0 0
0 1 1
we need to calculate minimum moves to convert this to all '0' matrix
0 0 0
0 0 0
0 0 0
Here,
For square of size 1 ( 1 X 1 or single element sub-matrix), the total number of moves required to convert this matrix is 4 . he converts elements for position (1,2),(1,3),(3,2),(3,3)
For square of size 2 ( 2 X 2 or single element sub-matrix), it takes 2 moves to convert the matrix
First we can convert elements from (1,2) to (2,3) and the matrix becomes, {{0 0 0}, {0 1 1}, {0 1 1}}
And then we convert elements from (2,2)to (3,3) and the matrix becomes ``{{0 0 0}, {0 0 0}, {0 0 0}}```
So minimum is 2.
Could some help in designing an approach to this ?
I attempted to solve it using Gaussian elimination for every possible square size. But the result is not correct here. There must be some gap in my approach to this problem.
package com.practice.hustle;
import java.util.Arrays;
public class GaussianElimination {
public static void main(String[] args) {
int countMoves = Integer.MAX_VALUE;
byte[][] inputMatrix = new byte[3][3];
inputMatrix[0][0] = 0;
inputMatrix[0][1] = 1;
inputMatrix[0][2] = 1;
inputMatrix[1][0] = 0;
inputMatrix[1][1] = 0;
inputMatrix[1][2] = 0;
inputMatrix[2][0] = 0;
inputMatrix[2][1] = 1;
inputMatrix[2][2] = 1;
int N = inputMatrix.length;
int M = inputMatrix[0].length;
int maxSize = Math.min(N, M);
for (int j = 2; j <= maxSize; ++j) { // loop for every possible square size
byte[][] a = new byte[N * M][(N * M) + 1];
for (int i = 0; i < N * M; i++) { // logic for square wise toggle for every element of N*M elements
byte seq[] = new byte[N * M + 1];
int index_i = i / M;
int index_j = i % M;
if (index_i <= N - j && index_j <= M - j) {
for (int c = 0; c < j; c++) {
for (int k = 0; k < j; k++) {
seq[i + k + M * c] = 1;
}
}
a[i] = seq;
} else {
if (index_i > N - j) {
seq = Arrays.copyOf(a[i - M], N * M + 1);
} else {
seq = Arrays.copyOf(a[i - 1], N * M + 1);
}
}
seq[N * M] = inputMatrix[index_i][index_j];
a[i] = seq;
}
System.out.println("\nSolving for square size = " + j);
print(a, N * M);
int movesPerSquareSize = gaussian(a);
if (movesPerSquareSize != 0) { // to calculate minimum moves
countMoves = Math.min(countMoves, movesPerSquareSize);
}
}
System.out.println(countMoves);
}
public static int gaussian(byte a[][]) {
// n X n+1 matrix
int N = a.length;
for (int k = 0; k < N - 1; k++) {
// Finding pivot element
int max_i = k, max_value = a[k][k];
for (int i = k + 1; i < N; i++) {
if (a[i][k] > max_value) {
max_value = a[i][k];
max_i = i;
}
}
// swap max row with kth row
byte[] temp = a[k];
a[k] = a[max_i];
a[max_i] = temp;
// convert to 0 all cells below pivot in the column
for (int i = k+1; i < N; i++) {
// int scalar = a[i][k] + a[k][k]; // probability of a divide by zero
if (a[i][k] == 1) {
for (int j = 0; j <= N; j++) {
if (a[i][j] == a[k][j]) {
a[i][j] = 0;
} else {
a[i][j] = 1;
}
}
}
}
}
System.out.println("\n\tAfter applying gaussian elimination : ");
print(a, N);
int count = 0;
for (int i = 0; i < N; i++) {
if (a[i][N] == 1)
++count;
}
return count;
}
private static void print(byte[][] a, int N) {
for (int i = 0; i < N; i++) {
System.out.print("\t ");
for (int j = 0; j < N + 1; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println(" ");
}
}
}
Its giving final reduced Euler matrix formed is incorrect and thereby the result is also incorrect.
I think its failing due to the logic used for element like - the cell at index-(2,3) , for that we are not sure which square would it be a part of ( either the square from (1,2) to (2,3) or the square from ( 2,2) to (3,3))
here the input matrix to Gaussian algo is having exactly same sequence at 2nd and 3rd row which could be the culprit of incorrect results.
1 1 0 1 1 0 0 0 0 0
* 0 1 1 0 1 1 0 0 0 1 *
* 0 1 1 0 1 1 0 0 0 1 *
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 0
0 0 0 0 1 1 0 1 1 0
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 1 1 0 1 1 1
for a sqaure size 2, the above program prints :
Solving for square size = 2
The input to Gaussian algo :
1 1 0 1 1 0 0 0 0 0
0 1 1 0 1 1 0 0 0 1
0 1 1 0 1 1 0 0 0 1
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 0
0 0 0 0 1 1 0 1 1 0
0 0 0 1 1 0 1 1 0 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 1 1 0 1 1 1
After applying gaussian elimination :
1 0 1 0 0 0 1 0 1 1
0 1 1 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 1 1 0 1 0
0 0 0 0 1 1 0 1 1 1
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 1

Python3 : unpack requires a bytes object of length 117

I am trying to run script for astronomical algorithm VSOP2013.
but when I running this script, it displays error in line 178
how to solve it?
What's wrong with unpack function?
FYI, the original script is python2, i am using python3
a = self.fmt.unpack(terms.encode())
error: unpack requires a bytes object of length 117
This is my full python3 script, adapted from the original python2 version from http://domenicomustara.blogspot.co.id
# -*- coding: utf-8 -*-
import gmpy2 as gmp
import struct
import ctypes
gmp.get_context().precision=200
def cal2jul(year, month, day, hour=0, minute =0, second=0):
month2 = month
year2 = year
if month2 <= 2:
year2 -= 1
month2 += 12
if (year*10000 + month*100 + day) > 15821015:
a = int(year2/100)
b = 2 - a + int(a/4)
else:
a = 0
b = 0
if year < 0:
c = int((365.25 * year2)-0.75)
else:
c = int(365.25 * year2)
d = int(30.6001 *(month2 + 1))
return b + c + d + day + hour / 24.0 + minute / 1440.0 + second / 86400.0 + 1720994.5
class VSOP2013():
def __init__(self, t, planet, precision=1e-7):
# calculate millennia from J2000
self.JD = t
self.t = gmp.div((t - cal2jul(2000,1,1,12)), 365250.0)
# predefine powers of self.t
self.power = []; self.power.append(gmp.mpfr(1.0)); self.power.append(self.t)
for i in range(2,21):
t = self.power[-1]
self.power.append(gmp.mul(self.t,t))
# choose planet file in a dict
self.planet = planet
self.planets = {'Mercury':'VSOP2013p1.dat',
'Venus' :'VSOP2013p2.dat',
'EMB' :'VSOP2013p3.dat',
'Mars' :'VSOP2013p4.dat',
'Jupiter':'VSOP2013p5.dat',
'Saturn' :'VSOP2013p6.dat',
'Uranus' :'VSOP2013p7.dat',
'Neptune':'VSOP2013p8.dat',
'Pluto' :'VSOP2013p9.dat'}
# VSOP2013 routines precision
self.precision = precision
# lambda coefficients
# l(1,13) : linear part of the mean longitudes of the planets (radian).
# l(14): argument derived from TOP2013 and used for Pluto (radian).
# l(15,17) : linear part of Delaunay lunar arguments D, F, l (radian).
self.l = (
(gmp.mpfr(4.402608631669), gmp.mpfr(26087.90314068555)),
(gmp.mpfr(3.176134461576), gmp.mpfr(10213.28554743445)),
(gmp.mpfr(1.753470369433), gmp.mpfr(6283.075850353215)),
(gmp.mpfr(6.203500014141), gmp.mpfr(3340.612434145457)),
(gmp.mpfr(4.091360003050), gmp.mpfr(1731.170452721855)),
(gmp.mpfr(1.713740719173), gmp.mpfr(1704.450855027201)),
(gmp.mpfr(5.598641292287), gmp.mpfr(1428.948917844273)),
(gmp.mpfr(2.805136360408), gmp.mpfr(1364.756513629990)),
(gmp.mpfr(2.326989734620), gmp.mpfr(1361.923207632842)),
(gmp.mpfr(0.599546107035), gmp.mpfr(529.6909615623250)),
(gmp.mpfr(0.874018510107), gmp.mpfr(213.2990861084880)),
(gmp.mpfr(5.481225395663), gmp.mpfr(74.78165903077800)),
(gmp.mpfr(5.311897933164), gmp.mpfr(38.13297222612500)),
(gmp.mpfr(0.000000000000), gmp.mpfr(0.3595362285049309)),
(gmp.mpfr(5.198466400630), gmp.mpfr(77713.7714481804)),
(gmp.mpfr(1.627905136020), gmp.mpfr(84334.6615717837)),
(gmp.mpfr(2.355555638750), gmp.mpfr(83286.9142477147)))
# planetary frequencies in longitude
self.freqpla = {'Mercury' : gmp.mpfr(0.2608790314068555e5),
'Venus' : gmp.mpfr(0.1021328554743445e5),
'EMB' : gmp.mpfr(0.6283075850353215e4),
'Mars' : gmp.mpfr(0.3340612434145457e4),
'Jupiter' : gmp.mpfr(0.5296909615623250e3),
'Saturn' : gmp.mpfr(0.2132990861084880e3),
'Uranus' : gmp.mpfr(0.7478165903077800e2),
'Neptune' : gmp.mpfr(0.3813297222612500e2),
'Pluto' : gmp.mpfr(0.2533566020437000e2)}
# target variables
self.ax = gmp.mpfr(0.0) # major semiaxis
self.ml = gmp.mpfr(0.0) # mean longitude
self.kp = gmp.mpfr(0.0) # e*cos(perielium longitude)
self.hp = gmp.mpfr(0.0) # e*sin(perielium longitude)
self.qa = gmp.mpfr(0.0) # sin(inclination/2)*cos(ascending node longitude)
self.pa = gmp.mpfr(0.0) # sin(inclination/2)*cos(ascending node longitude)
self.tg_var = {'A':self.ax, 'L':self.ml, 'K':self.kp,
'H':self.hp, 'Q':self.qa, 'P':self.pa }
# eps = (23.d0+26.d0/60.d0+21.41136d0/3600.d0)*dgrad
self.eps = gmp.mpfr((23.0+26.0/60.0+21.411360/3600.0)*gmp.const_pi()/180.0)
self.phi = gmp.mpfr(-0.051880 * gmp.const_pi() / 180.0 / 3600.0)
self.ceps = gmp.cos(self.eps)
self.seps = gmp.sin(self.eps)
self.cphi = gmp.cos(self.phi)
self.sphi = gmp.sin(self.phi)
# rotation of ecliptic -> equatorial rect coords
self.rot = [[self.cphi, -self.sphi*self.ceps, self.sphi*self.seps],
[self.sphi, self.cphi*self.ceps, -self.cphi*self.seps],
[0.0, self.seps, self.ceps ]]
self.fmt = struct.Struct("""6s 3s 3s 3s 3s x 3s 3s 3s 3s 3s x 4s 4s 4s 4s x
6s x 3s 3s 3s 20s x 3s 20s x 3s x""")
self.gmp_ = {
'Mercury' : gmp.mpfr(4.9125474514508118699e-11),
'Venus' : gmp.mpfr(7.2434524861627027000e-10),
'EMB' : gmp.mpfr(8.9970116036316091182e-10),
'Mars' : gmp.mpfr(9.5495351057792580598e-11),
'Jupiter' : gmp.mpfr(2.8253458420837780000e-07),
'Saturn' : gmp.mpfr(8.4597151856806587398e-08),
'Uranus' : gmp.mpfr(1.2920249167819693900e-08),
'Neptune' : gmp.mpfr(1.5243589007842762800e-08),
'Pluto' : gmp.mpfr(2.1886997654259696800e-12)}
self.gmsol = gmp.mpfr(2.9591220836841438269e-04)
self.rgm = gmp.sqrt(self.gmp_[self.planet]+self.gmsol)
# run calculus routine
self.calc()
def __str__(self):
vsop_out = "{:3.13} {:3.13} {:3.13} {:3.13} {:3.13} {:3.13}\n".format(
self.tg_var['A'],
self.tg_var['L'],
self.tg_var['K'],
self.tg_var['H'],
self.tg_var['Q'],
self.tg_var['P'])
vsop_out += "{:3.13} {:3.13} {:3.13} {:3.13} {:3.13} {:3.13}\n".format(
self.ecl[0],
self.ecl[1],
self.ecl[2],
self.ecl[3],
self.ecl[4],
self.ecl[5])
vsop_out += "{:3.13} {:3.13} {:3.13} {:3.13} {:3.13} {:3.13}\n".format(
self.equat[0],
self.equat[1],
self.equat[2],
self.equat[3],
self.equat[4],
self.equat[5])
return vsop_out
def calc(self):
with open(self.planets[self.planet]) as file_in:
terms = []
b = '*'
while b != '':
b = file_in.readline()
if b != '':
if b[:5] == ' VSOP':
header = b.split()
#print header[3], header[7], header[8], self.t**int(header[3])
no_terms = int(header[4])
for i in range(no_terms):
#6x,4i3,1x,5i3,1x,4i4,1x,i6,1x,3i3,2a24
terms = file_in.readline()
# print('terms',terms)
a = self.fmt.unpack(terms.encode())
S = gmp.mul(gmp.mpfr(a[18]),gmp.exp10(int(a[19])))
C = gmp.mul(gmp.mpfr(a[20]),gmp.exp10(int(a[21])))
if gmp.sqrt(S*S+C*C) < self.precision:
break
aa = 0.0; bb = 0.0;
for j in range(1,18):
aa += gmp.mul(gmp.mpfr(a[j]), self.l[j-1][0])
bb += gmp.mul(gmp.mpfr(a[j]), self.l[j-1][1])
arg = aa + bb * self.t
power = int(header[3])
comp = self.power[power] * (S * gmp.sin(arg) + C * gmp.cos(arg))
if header[7] == 'L' and power == 1 and int(a[0]) == 1:
pass
else:
self.tg_var[header[7]] += comp
self.tg_var['L'] = self.tg_var['L'] + self.t * self.freqpla[self.planet]
self.tg_var['L'] = self.tg_var['L'] % (2 * gmp.const_pi())
if self.tg_var['L'] < 0:
self.tg_var['L'] += 2*gmp.const_pi()
print ("Julian date {}".format(self.JD))
file_in.close()
##print self.tg_var
#### def ELLXYZ(self):
xa = self.tg_var['A']
xl = self.tg_var['L']
xk = self.tg_var['K']
xh = self.tg_var['H']
xq = self.tg_var['Q']
xp = self.tg_var['P']
# Computation
xfi = gmp.sqrt(1.0 -xk * xk - xh * xh)
xki = gmp.sqrt(1.0 -xq * xq - xp * xp)
u = 1.0/(1.0 + xfi)
z = complex(xk, xh)
ex = abs(z)
ex2 = ex * ex
ex3 = ex2 * ex
z1 = z.conjugate()
#
gl = xl % (2*gmp.const_pi())
gm = gl - gmp.atan2(xh, xk)
e = gl + (ex - 0.1250 * ex3) * gmp.sin(gm)
e += 0.50 * ex2 * gmp.sin(2.0 * gm)
e += 0.3750 * ex3 * gmp.sin(3.0 * gm)
#
while True:
z2 = complex(0.0, e)
zteta = gmp.exp(z2)
z3 = z1 * zteta
dl = gl - e + z3.imag
rsa = 1.0 - z3.real
e = e + dl / rsa
if abs(dl) < 1e-15:
break
#
z1 = u * z * z3.imag
z2 = gmp.mpc(z1.imag, -z1.real)
zto = (-z+zteta+z2)/rsa
xcw = zto.real
xsw = zto.imag
xm = xp * xcw - xq * xsw
xr = xa * rsa
#
self.ecl = []; self.equ = {}
self.ecl.append(xr * (xcw -2.0 *xp * xm))
self.ecl.append(xr * (xsw +2.0 *xq * xm))
self.ecl.append(-2.0 * xr * xki * xm)
#
xms = xa *(xh + xsw) / xfi
xmc = xa *(xk + xcw) / xfi
xn = self.rgm / xa ** (1.50)
#
self.ecl.append( xn *((2.0 * xp * xp - 1.0) * xms + 2.0 * xp * xq * xmc))
self.ecl.append( xn *((1.0 -2.0 * xq * xq) * xmc -2.0 * xp * xq * xms))
self.ecl.append( 2.0 * xn * xki * (xp * xms + xq * xmc))
# Equatorial rectangular coordinates and velocity
#
#
# --- Computation ------------------------------------------------------
#
self.equat = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
for i in range(3):
for j in range(3):
self.equat[i] = self.equat[i] + self.rot[i][j] * self.ecl[j]
self.equat[i+3] = self.equat[i+3] + self.rot[i][j] * self.ecl[j+3]
if __name__ == '__main__':
for planet in ('Mercury', 'Venus', 'EMB', 'Mars', 'Jupiter',
'Saturn', 'Uranus', 'Neptune', 'Pluto'):
print ("PLANETARY EPHEMERIS VSOP2013 "+ planet + "(TDB)\n"+"""
1/ Elliptic Elements: a (au), lambda (radian), k, h, q, p - Dynamical Frame J2000
2/ Ecliptic Heliocentric Coordinates: X,Y,Z (au) X',Y',Z' (au/d) - Dynamical Frame J2000
3/ Equatorial Heliocentric Coordinates: X,Y,Z (au) X',Y',Z' (au/d) - ICRS Frame J2000
""")
init_date = cal2jul(1890,6,26,12)
set_date = init_date
while set_date < init_date + 41000:
v = VSOP2013(set_date, planet)
print (v)
set_date += 4000
Respond comment from Mr.barrycarter,
this is a bit of the result when i print(terms.encode()):
b' 2 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0.6684459764580090 -07 0.3603178002233933 -06\n'
b' 3 0 2 -4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.2383757728520679 -07 0.9861749707454420 -07\n'
b' 4 0 4 -6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -0.2193692495097233 -07 -0.8959173003201546 -07\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 0.1017891898227051 -03\n'
b' 2 0 3 -5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.4236543085970792 -07 -0.8775084424897674 -08\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 0.4702795245810685 -04\n'
b' 2 0 3 -5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -0.5710471800210820 -09 -0.1800837750117577 -08\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 -0.5421827377115325 -06\n'
b' 2 0 3 -5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -0.7074507338012408 -10 0.1742474656298139 -10\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 -0.2508633795522544 -07\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 0.4575014479216901 -09\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 0.5208591612817609 -11\n'
b' 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0000000000000000 +00 -0.1737141639583644 -12'

Efficiently unpack a vector into binary matrix Octave

On Octave I'm trying to unpack a vector in the format:
y = [ 1
2
4
1
3 ]
I want to return a matrix of dimension ( rows(y) x max value(y) ), where for each row I have a 1 in the column of the original digits value, and a zero everywhere else, i.e. for the example above
y01 = [ 1 0 0 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0 ]
so far I have
y01 = zeros( m, num_labels );
for i = 1:m
for j = 1:num_labels
y01(i,j) = (y(i) == j);
end
end
which works, but is going get slow for bigger matrices, and seems inefficient because it is cycling through every single value even though the majority aren't changing.
I found this for R on another thread:
f3 <- function(vec) {
U <- sort(unique(vec))
M <- matrix(0, nrow = length(vec),
ncol = length(U),
dimnames = list(NULL, U))
M[cbind(seq_len(length(vec)), match(vec, U))] <- 1L
M
}
but I don't know R and I'm not sure if/how the solution ports to octave.
Thanks for any suggestions!
Use a sparse matrix (which also saves a lot of memory) which can be used in further calculations as usual:
y = [1; 2; 4; 1; 3]
y01 = sparse (1:rows (y), y, 1)
if you really want a full matrix then use "full":
full (y01)
ans =
1 0 0 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
Sparse is a more efficient way to do this when the matrix is big.
If your dimension of the result is not very high, you can try this:
y = [1; 2; 4; 1; 3]
I = eye(max(y));
y01 = I(y,:)
The result is same as full(sparse(...)).
y01 =
1 0 0 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
% Vector y to Matrix Y
Y = zeros(m, num_labels);
% Loop through each row
for i = 1:m
% Use the value of y as an index; set the value matching index to 1
Y(i,y(i)) = 1;
end
Another possibility is:
y = [1; 2; 4; 1; 3]
classes = unique(y)(:)
num_labels = length(classes)
y01=[1:num_labels] == y
With the following detailed printout:
y =
1
2
4
1
3
classes =
1
2
3
4
num_labels = 4
y01 =
1 0 0 0
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0

construct a matrix in Octave

I have a vector idx = [3; 5; 3; 4; 3; 2; 5; 1]. The number is from 1:k with k = 5. I want to make a "k by m" matrix A (m is the number of elements in the vector idx). Each row of A contains either '0' or '1' with '1' indicated by the index of the vector idx. For example, the third row of A (k = 3) is "1" at columns 1, 3, 5 because those are the indexes of "3" in idx. So that A =
[0 0 0 0 0 0 0 1; 0 0 0 0 1 0 0 0; 1 0 1 0 1 0 0 0; 0 0 0 1 0 0 0 0; 0 1 0 0 0 0 1 0]
How can I do this in Octave? Thank you!
Or another way:
idx = [3; 5; 3; 4; 3; 2; 5; 1];
A = sparse (idx, [1:numel(idx)], 1)
A = Compressed Column Sparse (rows = 5, cols = 8, nnz = 8 [20%])
(3, 1) -> 1
(5, 2) -> 1
(3, 3) -> 1
(4, 4) -> 1
(3, 5) -> 1
(2, 6) -> 1
(5, 7) -> 1
(1, 8) -> 1
Which gives you a compressed column sparse (very efficient), you can convert this to a "normal, full matrix":
B = full (A)
B =
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
1 0 1 0 1 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 1 0
Try this:
idx = [3; 5; 3; 4; 3; 2; 5; 1];
n = numel(idx);
k = 5;
A=zeros(k,n);
A(sub2ind(size(A), idx, [1:n]')) = 1
Output is:
A =
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
1 0 1 0 1 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 1 0

Matlab file input

I am asking this as a person with no experience in Matlab.
The project is simple; write a code to analyse a simple truss. The following is what a team mate has been working on - I'm supposed to write the input file:
file = input('File Input): ', 's');
run(file)
%Cc corresponds to # of joints and Rc corresponds to # of members
[Rc Cc] = size(C);
%JM is a matrix that contains the joint numbers that each member is
%connected to. The row number is the member number
JM = zeros(Cc, 2);
%x components
Ax = zeros(Rc, Cc);
%y components
Ay = zeros(Rc, Cc);
My_total_length = 0;
Member_length = 0;
%finding JM matrix which stores the joints that each member is connected to
%loop through C matrix and store the joint number each member is connected
%to
for j = 1:Cc
counter = 0;
for i = 1:Rc
if C(i,j) == 1
counter = counter + 1;
JM(j, counter) = i;
end
end
end
%using JM, loop through C again and create the equilibrium equations using
%the locations of each joint X and Y
for j = 1:Cc
counter = 3;
for i = 1:Rc
if C(i,j) == 1
%use counter to get x2 - x1 from JM vector
counter = counter - 1;
%find x and y distance of member and divide it by length of the member
Member_length = sqrt(((X(JM(j,2))) - ...
(X(JM(j,1))))^2 + ((Y(JM(j,2))) - (Y(JM(j,1))))^2);
Ax(i,j) = (X(JM(j,counter)) - X(i)) / Member_length; ! 13!
Ay(i,j)= (Y(JM(j, counter)) - Y(i)) / Member_length;
end
end
My_total_length = My_total_length + Member_length;
end
%combine the 4 matrices to create the larger matrix A
A = [Ax Sx; Ay Sy];
%define the vector for the forces on each member
T = zeros(Cc +3, 1);
T = inv(A)*-L;
%OUTPUT
%Find what the load on the truss is by looping through the weight vector and finding the load
for i=1:length(L)
if L(i) ~= 0
Load = L(i);
end
end
%Display load
fprintf('Load: %f N \n',Load)
%Display the forces on the members. Loop through Vector T up to the where reaction forces are
fprintf('Member forces in Newtons: \n')
for i = 1:length(T)-3
if (T(i)<0)
fprintf('m%d: %2.3f (C) \n', i, abs(T(i)))
elseif (T(i)==0)
fprintf('m%d: %d \n', i, abs(T(i)))
else
fprintf('m%d: %2.3f (T) \n', i, abs(T(i)))
end
end
%Display the last three items of vector T, the reaction forces
fprintf('Reaction forces in Newtons: \nSx1: %2.3f \nSy1: %2.3f \nSy2: %2.3f \n'...
, T(length(T)-2), T(length(T)-1), T(end))
%Calculate cost of truss
Cost = Rc*(10) + My_total_length*(1);
%Display the cost of truss
fprintf('Cost of truss: $%3.2f \n', Cost)
%Display load/cost ratio
fprintf('Theoretical max load/cost ratio in N/$: %2.4f \n', (Load/Cost))
Now, the problem I have is actually the input file. What kind of file should I save it as? How do I write it in the file? When I'm trying to run the code and need to access the file, how do I write the file name (with .txt after)? Some of the information that has to go into the file is below:
Sx = [ 1 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0, 0 0 0; 0 0 0]
Sy = [ 0 1 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 0; 0 0 1]
C = [ 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ; 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]
L = [ 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 500; 0; 0; 0; 0; 0]
X = [ 0,6,12,18,24,30,36,42,48,54,60]
Y = [ 0,8,0,8,0,8,0,8,0,8,0]
Would truly appreciate any help.
You can use fwrite to write to a txt file. This does however need fread and so code to read it into matlab again. xlswrite and xlsread does the same for xls files.
However, the simplest way if a file only is to be used together with matlab is to use the functions load and save. You can read the help for them with help save or help load, but the can save one or more variables to a .mat file.
a = 1;
b = 'e';
c = [1,2;3,4];
d = struct('hi',1,'you','e');
save('myFileName.mat','a','b','c','d');
clear;
load('myFileName.mat')
You can also write filepath/filename (or \ for windows) where filepath is the full path.

Resources