Mat2tex.java
/*
* $Id: Mat2tex.java,v 1.9 2008/02/25 08:35:52 koga Exp $
*
* Copyright (C) 2004 Koga Laboratory. All rights reserved.
*/
package org.mklab.tool.matrix;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import org.mklab.nfc.matrix.DoubleMatrix;
/**
* 行列をTeX形式でファイルに保存するクラスです。
*
* <p> Save a matrix to a file in tex-form
*
* @author koga
* @version $Revision: 1.9 $
* @see org.mklab.tool.matrix.Poly2tex
* @see org.mklab.tool.matrix.Rat2tex
*/
public class Mat2tex {
/**
* @param A 対象となる行列
* @param file ファイル名
* @throws IOException 出力できない場合
*/
public static void mat2tex(DoubleMatrix A, String file) throws IOException {
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
pw.print(mat2texf(A));
}
}
/**
* @param A 対象となる行列
* @param file ファイル名
* @param fmt 数値の形式
* @throws IOException 出力できない場合
*/
public static void mat2tex(DoubleMatrix A, String file, NumberFormat fmt) throws IOException {
try (PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)))) {
pw.print(mat2texf(A, fmt));
}
}
/**
* @param A 対象となる行列
* @return TeX形式の文字列
*/
@SuppressWarnings("nls")
public static String mat2texf(DoubleMatrix A) {
String tex = "\\left[\\begin{array}{";
for (int i = 1; i <= A.getColumnSize(); i++) {
tex = tex + "r";
}
tex = tex + "}\n";
for (int i = 1; i <= A.getRowSize(); i++) {
tex = tex + " ";
for (int j = 1; j <= A.getColumnSize(); j++) {
tex = tex + A.getDoubleElement(i, j);
if (j != A.getColumnSize()) {
tex = tex + " & ";
}
}
if (i != A.getRowSize()) {
tex = tex + "\\\\ ";
}
tex = tex + "\n";
}
return tex + "\\end{array}\\right]\n";
}
/**
* @param A 対象となる行列
* @param fmt 数値の形式
* @return TeX形式の文字列
*/
@SuppressWarnings("nls")
public static String mat2texf(DoubleMatrix A, NumberFormat fmt) {
String tex = "\\left[\\begin{array}{";
for (int i = 1; i <= A.getColumnSize(); i++) {
tex = tex + "r";
}
tex = tex + "}\n";
for (int i = 1; i <= A.getRowSize(); i++) {
tex = tex + " ";
for (int j = 1; j <= A.getColumnSize(); j++) {
tex = tex + fmt.format(A.getDoubleElement(i, j));
if (j != A.getColumnSize()) {
tex = tex + " & ";
}
}
if (i != A.getRowSize()) {
tex = tex + "\\\\ ";
}
tex = tex + "\n";
}
return tex + "\\end{array}\\right]\n";
}
}