2

我在 R 中编写了一些代码来仅使用基本图形生成史密斯图。我对情节本身很满意,但我想改进代码。特别是我不确定这 4 个lapply调用,我想应该有一种更直接的方法来在基础 R 中绘制一组线。

下面是我正在使用的代码,以及它生成的图。我是 stackoverflow 的新手,所以如果我应该包含更多评论或提供更多信息,请告诉我。

#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)

# given z = r + jx, calculates complex number gamma = (z-1)/(z+1)
mapping <- function(r, x) {
                z <- complex(real = r, imaginary = x); (z-1)/(z+1)}
complex_line <- function(a) {lines(Re(a), Im(a), lwd = 0.5)}

plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)

dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2)
dd <- sort(unique(dd))

smith_grid <- function (value, step) {
  # applies conformal mapping to lines having contast r
  r_grid <- lapply(seq(0, value, step), 
    FUN = function(r){mapping(r, dd[dd >= -value & dd <= value])})
  # applies conformal mapping to lines having contast x
  x_grid <- lapply(seq(-value, value, step), 
    FUN = function(x){mapping(dd[dd >= 0 & dd <= value], x)})  

  lapply(r_grid, FUN=complex_line)
  lapply(x_grid, FUN=complex_line)
}

smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)

dev.off()

在此处输入图像描述

4

1 回答 1

2

根据 Carl Witthoft 的评论修改代码:

#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)

# applies conformal map (z-1)/(z+1) to complex number z
cmap <- function(z) (z-1)/(z+1)

plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)

dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2) # fix roundoff errors
dd <- sort(unique(dd)) # remove duplicates

smith_grid <- function (val, step) {
  # applies conformal map to lines having fixed real component
  r_grid <- outer(1i * dd[dd >= -val & dd <= val], seq(0, val, step), '+')
  r_grid <- cmap(r_grid)
  matlines(Re(r_grid), Im(r_grid), lwd = 0.5, col = 1, lty = 1)

  # applies conformal map to lines having fixed imaginary component
  x_grid <- outer(dd[dd >= 0 & dd <= val], 1i * seq(-val, val, step), '+')
  x_grid <- cmap(x_grid)
  matlines(Re(x_grid), Im(x_grid), lwd = 0.5, col = 1, lty = 1)
}

smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)

dev.off()
于 2013-09-13T12:37:26.453 回答