Skip to content
Files, Plotting, and Toolboxes
step 1/4

Reading — step 1 of 4

Learn

~2 min readLinear Algebra, Strings, Plotting

Octave is a numerical programming language but also an environment — files, plots, packages.

File I/O

%% Read a CSV-like data file
data = load("data.txt")          %% reads numerical values
data = csvread("data.csv")
data = textscan(fid, "%s %d %f")   %% structured

%% Write
save("data.mat", "data")          %% Octave/MATLAB binary
save("-text", "data.txt", "data")  %% text
csvwrite("out.csv", data)

File handles

fid = fopen("file.txt", "r");
while !feof(fid)
    line = fgetl(fid);
    %% process line
endwhile
fclose(fid);

Plotting

Octave's plot is the king feature for visualizing data:

x = 0:0.1:2*pi;
y = sin(x);

plot(x, y)
xlabel("x")
ylabel("sin(x)")
title("A sine wave")
grid on

%% Save to file
print("sine.png", "-dpng")

2D plots: plot, bar, histogram, scatter, area. 3D plots: mesh, surf, contour, surfc.

Multiple plots in one figure:

subplot(2, 1, 1); plot(x, sin(x));
subplot(2, 1, 2); plot(x, cos(x));

In Judge0 (no display), print("file.png") writes to disk if the filesystem allows; can't visualize interactively.

Statistics

Octave has statistics package (install via pkg install -forge statistics):

pkg load statistics

%% Distribution functions
x = randn(1000, 1);              %% 1000 samples from N(0,1)
[mu, sigma] = normfit(x)         %% fit
p = normpdf(x, mu, sigma)         %% density

%% Tests
[h, p] = ttest(x)                %% one-sample t-test

Other notable packages

  • signal — DSP
  • image — image processing
  • optim — optimization (nonlinear least squares, etc.)
  • symbolic — symbolic math (CAS)
  • io — extended I/O (Excel files, etc.)
  • parallel — parallelism

List installed: pkg list. Load: pkg load NAME.

MATLAB compatibility

95%+ MATLAB code runs in Octave. Differences:

  • Some toolboxes are commercial-only (Simulink, Stateflow)
  • Some plot styling differs slightly
  • Performance can differ — Octave is often slower for large matrices

For academic / personal use, Octave is free; MATLAB licenses cost thousands. The migration cost is usually low.

Profiling

profile on;
run_my_code();
profile off;
profshow();

Reports time per function. Optimize the slowest call paths.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…